<template>
	<view>
		<view class="page__content f-dc">
			<!-- <up-navbar :fixed="false" :title="titleName" :autoBack="false" :safeAreaInsetTop="true">
				<template #left>
					<view class="x-f navbar--left">
						<up-icon name="arrow-left" color="#fff" size="20" @click="goBack"></up-icon>

						<up-icon name="close" color="#fff" size="20" @click="goBack('close')"></up-icon>

					</view>
				</template>
				<template #right>

					<m-bubble type="list" :selectData="formMenus" position="right" topOption="right" bgcRgba="#fff"
						color="#333" @selectFun="TapPopup">
						<up-icon name="more-dot-fill" color="#fff" class="moremenu"></up-icon>
					</m-bubble>

				</template>
			</up-navbar> -->
			<uni-nav-bar :height="0" leftWidth="140rpx" rightWidth="60rpx" :title="titleName" :statusBar="true"
				:border="false" :fixed="true" :showMenuButtonWidth="true">
				<template #left>
					<view class="x-f navbar--left">
						<up-icon name="arrow-left" color="#fff" size="20" @click="goBack"></up-icon>

						<up-icon name="close" color="#fff" size="20" @click="goBack('close')"></up-icon>

					</view>
				</template>
				<template #right>
					<view class="x-ec" style="position: relative;">

						<m-bubble type="list" :selectData="formMenus" position="right" topOption="right" bgcRgba="#fff"
							color="#333" @selectFun="TapPopup">
							<up-icon name="more-dot-fill" size="20" color="#fff" class="moremenu"></up-icon>
						</m-bubble>

					</view>
				</template>
			</uni-nav-bar>


			<view class="page__content__top" v-if="isShowMainForm" :style="{flex: childFormList.length ? 'none' : 1}">
				<up-form labelPosition="left" :model="formData" ref="uForm" labelWidth="100"
					:labelStyle="{fontSize:'14px',fontWeight:600}">
					<up-form-item labelWidth="100" :label="row.baseProperty.labelName" prop="name" borderBottom
						:required="row.baseProperty.isRequired" v-for="(row,index) in formDesign" :key="index">
						<!-- v-for="(row,index) in getFilterData(formDesign,(ret) => ret.baseProperty.controlType != 'hidden')" :key="index"> -->

						<view v-if="row.baseProperty.controlType == 'datepicker'" @click="clickDatePicker(row)"
							style="width:100%">
							<up-input v-model="formData[row.baseProperty.controlName]"
								:ref="row.baseProperty.controlName" :readonly="true" border="none"
								v-if="row.baseProperty.controlType == 'datepicker'" suffixIcon="calendar"></up-input>
						</view>
						<view v-else-if="row.baseProperty.controlType=='select' && row.controlProperty.select.type == 1"
							@click="openBaseScreen(row)" style="width:100%">
							<up-input v-model="formData[row.baseProperty.controlName+'_show']"
								:name="row.baseProperty.controlName" suffixIcon="arrow-right" border="none"
								:readonly="true"></up-input>
						</view>
						<view v-else-if="row.baseProperty.controlType=='select' && row.controlProperty.select.type == 3"
							@click="openBaseScreen(row)" style="width:100%">
							<up-input v-model="formData[row.baseProperty.controlName+'_show']"
								:name="row.baseProperty.controlName" suffixIcon="arrow-right" border="none"
								:readonly="true"></up-input>
						</view>
						<up-input type="number" v-model="formData[row.baseProperty.controlName]"
							@change="dataChange(row)" :name="row.baseProperty.controlName" border="none"
							:readonly="row.baseProperty.isReadOnly" v-else-if="row.baseProperty.controlType == 'number'"
							:suffixIcon="row.baseProperty.isReadOnly ? '' : 'edit-pen-fill'"></up-input>
						<up-textarea v-else-if="row.baseProperty.controlType == 'textarea'" placeholder="请输入"
							v-model="formData[row.baseProperty.controlName]" :name="row.baseProperty.controlName"
							border="none" :readonly="row.baseProperty.isReadOnly" @change="dataChange(row)"
							:suffixIcon="row.baseProperty.isReadOnly ? '' : 'edit-pen-fill'"></up-textarea>

						<view v-else-if="row.baseProperty.controlType=='fileUpload'" style="width:100%">
							<m-upload v-model="formData[row.baseProperty.controlName + '_show']" useBeforeDelete
								@beforeDelete="beforeDelete" :uploadKey="row.baseProperty.controlName"
								:listStyle="{columns: BoxInfoCallBack.num,height:BoxInfoCallBack.height+'rpx',padding:'6px',columnGap:'10px',rowGap:'10px'}"
								cloudType="other" :action="uploadFile_action" @onSuccess="onSuccess"></m-upload>
						</view>

						<up-input v-else-if="row.baseProperty.controlType == 'textbox'" type="text"
							v-model="formData[row.baseProperty.controlName]" :name="row.baseProperty.controlName"
							border="none" :readonly="row.baseProperty.isReadOnly" @change="dataChange(row)"
							:suffixIcon="row.baseProperty.isReadOnly ? '' : 'edit-pen-fill'"></up-input>

					</up-form-item>
				</up-form>
			</view>
			<up-gap height="1" bgColor="#dadada"></up-gap>

			<view class="f-dc" style="overflow: auto;" :style="{flex: childFormList.length ?   1:'none'}">
				<!-- <up-icon name="order" ></up-icon> -->
				<!-- 导入数据，添加子表 -->

				<up-sticky bgColor="#fff" zIndex="11">
					<view class="x-bc">
						<up-row customStyle="margin-bottom: 10px;flex :1;overflow: auto hidden;"
							v-if="importConfig && filterImportConfigList().length>0">
							<up-col
								:span="12/(filterImportConfigList().length <= 4 ? filterImportConfigList().length : 4)"
								v-for="(importItem,index) in filterImportConfigList()" :key="index">
								<view class="x-c" @click="importData(importItem)"
									style="margin-top: 10px;height: 40rpx;">
									<up-icon name="order" color="#51d0d0" size="20"></up-icon>

									<text style="font-size: 24rpx;color: #51d0d0;">{{importItem.btnName}}</text>
								</view>
							</up-col>
						</up-row>

						<view v-if="filterImportConfigList().length > 4" @click="openImportSheet"
							style="height: 100%;width: 50px;border-left: 1px solid #e8e8e8;opacity: 0.8;" class="x-c">
							<up-icon name="grid-fill" color="#555555" size="28"></up-icon>
						</view>

					</view>
					<up-gap height="1" bgColor="#dadada"
						v-if="importConfig && filterImportConfigList().length>0"></up-gap>
					<up-tabs :list="TabList" keyName="title" :current="tabCurrent" @click="clickTabItem"
						:inactiveStyle="{ fontSize: '28rpx' }" :itemStyle="{height:'88rpx'}"
						:activeStyle="{ fontSize: '28rpx',color: '#51d0d0', fontWeight: '600', transform: 'scale(1.05)' }"></up-tabs>

				</up-sticky>

				<!-- <view :class="isShowMainForm?'Main_CardListBox':'Main_CardListBoxFull'" -->
				<view v-for="(childForm,index) in childFormList" :key="index">
					<up-empty mode="history" text="列表数据为空" marginTop="50"
						v-if="childForm.tableData && childForm.tableData.length==0 && childForm.title == TabList[tabCurrent]['title']">
					</up-empty>

					<up-swipe-action v-show="childForm.title == TabList[tabCurrent]['title']">
						<up-swipe-action-item :options="deleteOper"
							v-for="(item,idx) in childApproveShowFun(childForm.tableData)" :key="idx" :name="idx"
							@click="delRow(childForm,item)" ref="delSwiper" style="margin-bottom: 10rpx;">


							<view class="common__box__child__card" @click="openEditWin(item,childForm,idx)">
								<view class="common__box__child__card__top">
									<view class="common__box__child__card__top__left__title">

										<template v-if="childForm.hasOwnProperty('titleCol')">
											<template v-if="childForm.titleCol.colType!=2">
												<text class="van-badge">{{ idx+1 }}</text>
												<text>{{ item[childForm.titleCol.colName]}}</text>
											</template>

											<template v-else="childForm.titleCol.colType==2">
												<text class="van-badge">{{ idx+1 }}</text>
												<text>{{ showActualValue(item[childForm.titleCol.colName],childForm.titleCol ) }}</text>
											</template>
										</template>

										<template v-else>
											<text class="van-badge">{{ idx+1 }}</text>
										</template>
									</view>
								</view>

								<view class="common__box__child__card__content">

								</view>

								<!-- <view style="clear: both;"></view>
								<view class="content_main_CardBox_RightTop y-end"
									style="position: absolute;right: 20rpx;top: 50%;">
									<view class="FiledBox">
										<up-icon name="arrow-right"></up-icon>
									</view>
								</view> -->
								<view class="common__box__child__card__content__field"
									v-for="col in getFilterData(childForm.columns,(ret) => !ret.isHidden && !ret.isTitle )"
									:key="col.colName">
									<text class="common__box__child__card__content__field__required"
										:style="{visibility: col.isRequired ? 'initial':'hidden'}">*</text>

									<view class="common__box__child__card__content__field__label">
										<text>{{ col.colDesc }}：</text>
									</view>

									<template v-if="col.colType==5">
										<view class="common__box__child__card__content__field__value">
											<text>{{ showFileTheNumFun(item[col.colName]) }}</text>
										</view>
									</template>
									<template v-else-if="col.colType!=2">
										<view class="common__box__child__card__content__field__value">
											<text>{{ item[col.colName] }}</text>
										</view>
									</template>
									<template v-else-if="col.colType==2">
										<view class="common__box__child__card__content__field__value">
											<text>{{ showActualValue(item[col.colName],col) }}</text>
										</view>
									</template>
								</view>
							</view>
							<view class="childBtns">

								<!-- <up-button
									v-for="work in getFilterData(childForm.workList,(ret) => btn_showConditionByChild(ret) )"
									color="#51d0d0" @click="selfChildWorkHandler(work,item)" type="primary" size="small"
									:text="work.name" style="width:auto;margin-right:10px;"></up-button> -->

								<button
									v-for="(work,ind) in getFilterData(childForm.workList,(ret) => btn_showConditionByChild(ret) )"
									:key="ind" color="#51d0d0" @click="selfChildWorkHandler(work,item)" type="primary"
									style="width:auto;margin-right:10px;" size="mini">
									<text>{{work.name}}</text>
								</button>
							</view>
						</up-swipe-action-item>
					</up-swipe-action>
				</view>
			</view>

			<view class="content_bottom1 x-ec" :style="uni.$utils.disposeSafeBottomFun()">

				<!-- 	<button v-if="!isUpdate && enabledSubmitBtn" class="CommonBtnSize workBtn" plain
				:disabled="!enabledSubmitBtn" @click="saveDraftInfo">保存草稿</button> -->

				<!-- 审批流 -->
				<button class="CommonBtnSize workBtn" plain style="margin-left: 10px;" :disabled="!enabledSubmitBtn"
					v-if="
					approvalConfig.isEnableApproval && (!formData.Status || formData.Status==3) && !formData.Approve &&
					workList.filter(function(item:any){ return item.name=='发起审批' }).length==0" @click="startApprove">
					<text>发起审批</text>
				</button>

				<button class="CommonBtnSize workBtn" plain style="margin-left: 10px;" :disabled="!enabledSubmitBtn"
					@click="formApprove"
					v-if="approvalConfig.isEnableApproval && formData.Status == 1 && isCurApproval">
					<text>审批单据</text>
				</button>

				<button class="CommonBtnSize workBtn" plain style="margin-left: 10px;" :disabled="!enabledSubmitBtn"
					@click="cancelApprove" v-if="approvalConfig.isEnableApproval && formData.Status == 1">
					<text>撤销审批</text>
				</button>

				<!-- content_bottom_primary_Btn -->
				<!-- <button class="CommonBtnSize workBtn" plain v-for="btn in workList" style="margin-left: 10px;"
				v-if="btn_showCondition(2,btn)" @click="selfWorkHandler(btn)">
				{{ btn.name }}
			</button> -->

				<!-- 当业务按钮存在一项时 -->
				<view v-if="MoreSheetList.length == 1 && btnAllowShowFun(MoreSheetList[0]['name'])">
					<button class="CommonBtnSize x-c content_bottom_primary_plainBtn" :class="buttonClasses"
						:style="buttonStyles" :disabled="!enabledSubmitBtn" plain v-for="(btn,index) in MoreSheetList"
						:key="index" style="margin-left: 10px;" @click="selfWorkHandler(btn)">
						{{ btn.name }}
					</button>
				</view>
				<!-- 当存在多项业务按钮时 -->
				<view v-else-if="MoreSheetList.length > 1">
					<!-- <up-button class="CommonBtnSize content_bottom_primary_plainBtn" style="margin-left: 10px;"
						:disabled="!enabledSubmitBtn" text="更多"></up-button> -->

					<button class="CommonBtnSize x-c content_bottom_primary_plainBtn" style="margin-left: 10px;"
						:disabled="!enabledSubmitBtn" @click="openMoreSheet">更多</button>

				</view>

				<view>
					<button class="CommonBtnSize btn-height content_bottom_primary_Btn" :disabled="!enabledSubmitBtn"
						style="margin-left: 10px;"
						v-if="!isUpdate && btn_showCondition(1,'新增') && btnAllowShowFun('新增')"
						@click="saveRow">提交</button>
					<button class="CommonBtnSize btn-height content_bottom_primary_Btn" :disabled="!enabledSubmitBtn"
						style="margin-left: 10px;" v-if="isUpdate && btn_showCondition(1,'编辑') && btnAllowShowFun('编辑')"
						@click="saveRow">提交</button>
				</view>
			</view>

		</view>
		<!-- 日期控件 -->
		<up-datetime-picker style="z-index: 9999999;" :maxDate="maxOickerDateTime" :show="showDatePicker"
			v-model="curDate" :mode="DateFormatType" @confirm="onDatePickerConfirm" @cancel="closeByPicker"
			:closeOnClickOverlay="true"></up-datetime-picker>

		<up-datetime-picker style="z-index: 9999999;" :maxDate="maxOickerDateTime" :show="showDatePicker2"
			v-model="curDate2" :mode="DateFormatType2" @confirm="onDatePickerConfirm2" @cancel="closeByPicker2"
			:closeOnClickOverlay="true"></up-datetime-picker>


		<uni-popup ref="EditWinPopup" type="bottom" @close="closeEditWin" @maskClick="closeEditWin"
			background-color="#fff" border-radius="10px 10px 0 0">

			<up-navbar v-if="!uni.$utils.isPda()" :fixed="false" :autoBack="false" :safeAreaInsetTop="false"
				left-icon=" ">
				<template #right>
					<view class="x-ec">
						<up-icon name="reload" @click="TapPopup({name:'子表刷新'})" color="#fff" size="28"></up-icon>
						<up-icon name="scan" @click="TapPopup({name:'扫码'})" color="#fff" size="28"></up-icon>
					</view>
				</template>
			</up-navbar>
			<view class="editDetail f-dc" :style="uni.$utils.disposeSafeBottomFun()">
				<view class="editDetail-formBox">
					<up-form labelPosition="left" :model="editValues" ref="dForm" labelWidth="100">
						<template v-for="(row,index) in editFrame.columns" :key="row.colName">

							<up-form-item :label="row.colDesc" borderBottom :required="row.isRequired"
								v-if="!row.isHidden">
								<view v-if="row.colType==3" @click="clickDatePicker2(row)" style="width:100%">
									<!-- <up-input v-model="editValues[row.colName]" readonly :ref="row.colName"
										inputAlign="right" border="none" suffixIcon="calendar"></up-input> -->

									<view class="x-bc" v-if="row.colType==3">
										<view class="flex-auto x-ec" :ref="row.colName">
											<text>{{editValues[row.colName]}}</text>
										</view>

										<view style="width: 18px;">
											<uni-icons v-if="!row.isReadOnly" type="calendar" size="18"
												color="#5e6d82"></uni-icons>
										</view>

									</view>


								</view>
								<view v-else-if="row.colType==2  && row.selDetail.type==1" @click="openBaseScreen2(row)"
									style="width:100%">

									<view class="x-bc">
										<view class="flex-auto x-ec">
											<text>{{showActualValue(editValues[row.colName],row)}}</text>
										</view>

										<view style="width: 18px;">
											<uni-icons v-if="!row.isReadOnly" type="right" size="18"
												color="#5e6d82"></uni-icons>
										</view>

									</view>

								</view>
								<view v-else-if="row.colType==2  && row.selDetail.type==3" @click="openBaseScreen2(row)"
									style="width:100%">

									<view class="x-bc">
										<view class="flex-auto x-ec">
											<text>{{showActualValue(editValues[row.colName],row)}}</text>
										</view>

										<view style="width: 18px;">
											<uni-icons v-if="!row.isReadOnly" type="right" size="18"
												color="#5e6d82"></uni-icons>
										</view>

									</view>
								</view>

								<up-input v-else-if="row.colType == 4" type="number" v-model="editValues[row.colName]"
									inputAlign="right" :name="row.colName"
									@blur="itemDataChange(row,editValues,editFrame,editValues[row.colName])"
									border="none" :readonly="row.isReadOnly"
									:suffixIcon="row.isReadOnly ? 'none' : 'edit-pen-fill'"></up-input>

								<view v-else-if="row.colType == 1" style="width: 100%;">

									<up-input type="text" v-model="editValues[row.colName]" inputAlign="right"
										:name="row.colName"
										@blur="itemDataChange(row,editValues,editFrame,editValues[row.colName])"
										border="none" :readonly="row.isReadOnly"
										:suffixIcon="row.isReadOnly ? 'none' : 'edit-pen-fill'"></up-input>

								</view>

								<view v-else-if="row.colType == 5" style="width: 100%;">
									<m-upload v-model="editValues[row.colName + '_show']" useBeforeDelete
										@beforeDelete="beforeDeleteByChild" :uploadKey="row.colName"
										:listStyle="{columns: BoxInfoCallBack.num,height:BoxInfoCallBack.height+'rpx',padding:'6px',columnGap:'10px',rowGap:'10px'}"
										cloudType="other" :action="uploadFile_action"
										@onSuccess="onSuccessByChild"></m-upload>
								</view>
							</up-form-item>

						</template>


					</up-form>

				</view>
				<view style="height: 70px;" class="x-c">
					<button class="CommonBtnSize content_bottom_primary_Btn" style="width:calc(100% - 40px); "
						@click="closeEditWin">确定</button>
				</view>
			</view>

		</uni-popup>

		<m-loading text="正在渲染" :value="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>


		<up-action-sheet :actions="MoreSheetList" safeAreaInsetBottom :closeOnClickOverlay="true" cancelText="取消"
			:closeOnClickAction="true" @select="selfWorkHandler" :show="showMoreSheet"
			@close="closeSheetBtn"></up-action-sheet>

	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed, reactive, nextTick } from 'vue';
	import { onLoad, onReady, onUnload, onBackPress } from "@dcloudio/uni-app";
	// import { Parser } from 'expr-eval';
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	// import mClUpload from '@/commonPage/components/cl-upload/cl-upload';
	import { run } from '@/commonPage/common/interpreter'
	import { Task, TimeUnits, TaskOptions, TaskType, TaskTriggerMode, Context } from '@/commonPage/common/task-queue/TaskQueue.ts';

	let layer = uni.$utils.layer;

	let formMenus = ref([
		{ name: '隐藏表头', value: '', icon: 'order' },
		{ name: '扫码', value: '', icon: 'scan' },
		{ name: '刷新', value: '', icon: 'reload' },
	]);
	let plug = ref<any>(null)
	function TapPopup(data : any) {
		const {
			name
		} = data;
		switch (name) {
			case '隐藏表头':
			case '显示表头': {
				isShowMainForm.value = name === '显示表头';
				formMenus.value[0].name = isShowMainForm.value ? '隐藏表头' : '显示表头';
				break;
			}
			case '扫码': {
				uni.$utils.$scanPopup.openScan({
					success: (res : any) => {
						dealScan(res.result);
					}
				})
				break;
			}
			case '子表刷新': {
				refreshEditValueCol(editFrame);
				break;
			}
			case '刷新': {
				initConfig(detailName.value);
				break;
			}
			case '打印机列表': {
				uni.$utils.layer.alert("暂不支持此功能");

				uni.navigateTo({
					url: '../Tool/printList'
				});
				break;
			}
			case '打印': {
				uni.$utils.layer.alert("暂不支持此功能");
				const connectDevice = uni.getStorageSync('connectDevice');
				if (connectDevice) {

					// #ifdef APP-HARMONY

					// #endif

					// #ifdef APP-PLUS

					let maxData : never[] = [];
					// eval(printConfig.value); // 注意：eval 有安全风险，建议使用其他方式替代

					// new Function(printConfig.value)();
					run(`
					${printConfig.value}
					`, {
						// 注入UniApp环境的API（如uni对象）
						uni: uni,
						printConfig: printConfig.value,
						post,
						layer
					})
					plug.value.printer({
						TSC: maxData
					}, (ret : any) => {
						// 处理打印结果
					});
					// #endif
				} else {
					uni.navigateTo({
						url: '../Tool/printList'
					});
				}
				break;
			}
			default:
				console.warn(`未处理的选项: ${name}`);
				break;
		}
	};
	//处理扫描结果
	function dealScan(scanData : any) {

		let text = 'formData'
		if (showEditWin.value) {
			text = 'editValues'
		};
		if (scanConfig.value) {
			// 判定当前页面已进行修改
			isFormModified.value = true;
			if (showEditWin.value) {


				let script = scanConfig.value.replace(/vm\./g, '');
				script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'editValues$1');
				// eval(script);
				// new Function(script)();

				// new Function('editValues', script)(editValues);
				run(`
				${script}
				`, {
					// 注入UniApp环境的API（如uni对象）
					uni: uni,
					editValues: editValues,
					layer,
					scanData,
					post,
					request,
					insertImportData,
					editFrame,
					refreshEditValueCol,
					itemDataChange,
					curSelectWindowObj2,
					showEditWin: showEditWin.value
				})

			} else {
				let script = scanConfig.value.replace(/vm\./g, '');
				script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');
				// eval(script);
				// new Function(script)();
				// new Function('formData', script)(formData);
				run(`
				${script}
				`, {
					// 注入UniApp环境的API（如uni对象）
					uni: uni,
					formData: formData,
					layer,
					scanData,
					post,
					request,
					insertImportData,
					refreshEditValueCol,
					editFrame,
					showEditWin: showEditWin.value
				})
			}
		}
		// let script = vm.scanConfig.replace(/\['/g, `vm.${text}['`);
		// script = script.replace(/\["/g, `vm.${text}[\\"`);
		// eval(script);
	};

	let isShowMainForm = ref(true);
	interface FormData {
		[key : string] : any; // 允许动态添加其他字段
	}
	let formData = reactive<FormData>({});

	let formDesign = ref<any>([]);
	// let curDateObj = reactive<any>({});
	let curDateObj = ref<any>({});
	let curDate = ref<any>(Number(new Date()));
	let showDatePicker = ref(false);
	// 日期控件最大时间
	const maxOickerDateTime = computed(() => {
		let now = new Date();

		// 增加一百年  
		now.setFullYear(now.getFullYear() + 100);

		// 将Date对象转换为时间戳  
		return now.getTime();
	});
	let DateFormatType = ref("date");
	function onDatePickerConfirm(valueData : any) {
		let value = valueData.value + '';
		if (value && !isNaN(Number(value))) {


			let dateFormat = 'yyyy-MM-dd';
			if (curDateObj.value.controlProperty.date && curDateObj.value.controlProperty.date.type) {
				dateFormat = curDateObj.value.controlProperty.date.type;
			}

			let dateDown = uni.$utils.dateFormat(new Date(Number(value)), dateFormat);
			formData[curDateObj.value.baseProperty.controlName] = dateDown;
			// formData[vm.curDateObj.baseProperty.controlName] = vm.Request.getRealDate(value).split(' ')[0];
		} else if (!value) {
			formData[curDateObj.value.baseProperty.controlName] = "";
		}
		dataChange(curDateObj.value);
		showDatePicker.value = false;
		// curDateObj = '';
		// Object.assign(curDateObj, {});
		curDateObj.value = {}
		curDate.value = Number(new Date());
	};
	function closeByPicker() {
		showDatePicker.value = false;
		curDate.value = Number(new Date());
	}
	//时间组件
	function clickDatePicker(row : any) {
		if (row.baseProperty.isReadOnly) {
			return false;
		} else {
			// Object.assign(curDateObj, row);
			curDateObj.value = row;


			let theDate = new Date();
			if (!uni.$utils.isEmpty(formData[row.baseProperty.controlName])) {
				theDate = new Date(formData[row.baseProperty.controlName]);
			}
			let dateFormat = 'yyyy-MM-dd';
			if (row.controlProperty.date && row.controlProperty.date.type) {
				dateFormat = row.controlProperty.date.type;
			}

			// 点击时间选项时，确认日期控件格式
			let DateFormatType1 = uni.$utils.getDateFormatType(dateFormat);
			DateFormatType.value = DateFormatType1;

			let dateDown = uni.$utils.dateFormat(theDate, dateFormat);
			curDate.value = new Date(dateDown);
			showDatePicker.value = true;
		}
	};


	let isFormModified = ref(false);
	function dataChange(formCol : any, returnValue : any = {}) {
		// 判定当前页面已进行修改
		isFormModified.value = true;
		if (formCol.baseProperty.controlCallBack) {

			let script = formCol.baseProperty.controlCallBack.replace(/vm\./g, '');
			script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');
			run(script, {
				// 注入UniApp环境的API（如uni对象）
				uni: uni,
				formData: formData,
				returnValue: returnValue,
				post,
				refreshEditValueCol,
				editFrame,
				layer
			});

			refreshInitActualName();
		};

		if (formCol.baseProperty.controlChange) {
			let script = formCol.baseProperty.controlChange.replace(/vm\./g, '');
			// script = script.replace(/(\['|["])/g, 'formData$1');
			script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');
			// eval(script);
			// new Function('formData', 'returnValue', script)(formData, returnValue);
			run(script, {
				// 注入UniApp环境的API（如uni对象）
				uni: uni,
				formData: formData,
				returnValue: returnValue,
				post,
				refreshEditValueCol,
				editFrame,
				layer
			})


			refreshInitActualName();
		}

		//判断当前列是否是下属列
		childFormList.value.forEach(function (childForm : any) {

			if (childForm.transParams.indexOf(formCol.baseProperty.controlName) >= 0) {

				transParamsDefault();
			}
		})
	};
	function refreshInitActualName() {
		for (let i = 0; i < formDesign.value.length; i++) {
			//日期控件，格式化内容
			if (formDesign.value[i].baseProperty.controlType == 'datepicker') {
				formData[formDesign.value[i].baseProperty.controlName] = formatterDate(
					formData[formDesign.value[i].baseProperty.controlName],
					(formDesign.value[i].controlProperty.date && formDesign.value[i].controlProperty.date.type) ? formDesign.value[i].controlProperty.date.type : "yyyy-MM-dd");
			}
			if (formDesign.value[i].baseProperty.controlType == "select") {
				//下拉框数据加载
				if (formDesign.value[i].controlProperty.select.type < 3) {
					let sql = formDesign.value[i].controlProperty.select.dataSource;

					let formDesignObj = formDesign.value[i];
					dealSelectDatasource(sql, formDesignObj);
				} else if (formDesign.value[i].controlProperty.select.type == 3) {

					if (formDesign.value[i].controlProperty.select.chooseType == 1) {
						let valueList = [];
						if (formData[formDesign.value[i].baseProperty.controlName] != undefined &&
							formData[
							formDesign.value[i].baseProperty.controlName] !== "") {
							valueList.push("'" + formData[formDesign.value[i].baseProperty
								.controlName] + "'");
						}
						let sql = "select * from (" + formDesign.value[i].controlProperty.select
							.dataSource +
							")t";
						if (valueList.length > 0) {
							sql += " where " + formDesign.value[i].controlProperty.select
								.hiddenValue + " in (" +
								valueList.join(',') + ") ";
							let formDesignObj = formDesign.value[i];
							dealSelectDatasourceByTree(sql, formDesignObj);
						} else {
							formDesign.value[i].controlProperty.select["sqlDataSource"] = [];
							formDesign.value[i].controlProperty.select["originDataSource"] = [];
							formDesign.value[i].controlProperty.select["actualName"] = "";

							formData[formDesign.value[i].baseProperty.controlName + '_show'] = '';
						}
					} else {
						let valueList = "";
						if (formData[formDesign.value[i].baseProperty.controlName] != undefined &&
							formData[
							formDesign.value[i].baseProperty.controlName] !== "") {
							let valueArray = [];
							valueArray = formData[formDesign.value[i].baseProperty.controlName].toString().split(',');
							for (let q = 0; q < valueArray.length; q++) {
								valueArray[q] = "'" + valueArray[q] + "'";
							}
							valueList = valueArray.join(',');
						}
						let formDesignObj = formDesign.value[i];
						let sql = "select * from (" + formDesign.value[i].controlProperty.select
							.dataSource +
							")t";
						if (valueList) {
							sql += " where " + formDesign.value[i].controlProperty.select
								.hiddenValue + " in (" +
								valueList + ") ";
							dealSelectDatasourceByTree(sql, formDesignObj);
						} else {

							formDesign.value[i].controlProperty.select["sqlDataSource"] = [];
							formDesign.value[i].controlProperty.select["originDataSource"] = [];
							formDesign.value[i].controlProperty.select["actualName"] = "";
							formData[formDesign.value[i].baseProperty.controlName + '_show'] = ''
						}
					}
				}
			};
		}
	};
	//传递参数，默认值
	async function transParamsDefault() {

		for (let i = 0; i < childFormList.value.length; i++) {
			let defaultParams = childFormList.value[i].defaultParams.split(',');
			let defaultChildParams = childFormList.value[i].defaultChildParams.split(',');

			for (let j = 0; j < defaultParams.length; j++) {
				childFormList.value[i].fixedValues[defaultChildParams[j]] = formData[defaultParams[j]];
			};

			let transParams = childFormList.value[i].transParams.split(',');
			let transChildParams = childFormList.value[i].transChildParams.split(',');
			for (let j = 0; j < transParams.length; j++) {
				childFormList.value[i].fixedValues[transChildParams[j]] = formData[transParams[j]];

				for (let x = 0; x < childFormList.value[i].tableData.length; x++) {
					childFormList.value[i].tableData[x][transChildParams[j]] = formData[transParams[j]];


					let filterData = columns.value.filter(item => {
						return item.colName == transParams[j];
					});
				}
			}

		}



		// childFormList.value.forEach((child : any) => {
		// 	// ----------- 1. 处理 defaultParams ----------
		// 	const defaultParams = child.defaultParams ? child.defaultParams.split(',') : [];
		// 	const defaultChildParams = child.defaultChildParams ? child.defaultChildParams.split(',') : [];


		// 	if (defaultParams.length && defaultChildParams.length) {
		// 		for (let j = 0; j < Math.min(defaultParams.length, defaultChildParams.length); j++) {
		// 			const key = defaultChildParams[j];
		// 			const srcKey = defaultParams[j];

		// 			if (key && srcKey) {
		// 				child.fixedValues[key] = formData?.[srcKey] ?? "";
		// 			}
		// 		}
		// 	}

		// 	// ----------- 2. 处理 transParams ----------
		// 	const transParams = child.transParams ? child.transParams.split(',') : [];
		// 	const transChildParams = child.transChildParams ? child.transChildParams.split(',') : [];

		// 	if (transParams.length && transChildParams.length) {
		// 		for (let j = 0; j < Math.min(transParams.length, transChildParams.length); j++) {
		// 			const key = transChildParams[j];
		// 			const srcKey = transParams[j];

		// 			if (key && srcKey) {
		// 				const val = formData?.[srcKey] ?? "";
		// 				child.fixedValues[key] = val;

		// 				// 同步到子表 tableData
		// 				if (Array.isArray(child.tableData)) {
		// 					child.tableData.forEach((tItem : any) => {
		// 						tItem[key] = val;
		// 					});
		// 				}
		// 			}
		// 		}
		// 	}
		// });
	}


	// 文件上传-删除指定数据事件
	function beforeDelete({ fileToDelete,
		uploadKey } : any, index : any, next : any) {
		uni.showModal({
			title: '提示信息',
			content: '确定要删除这个文件嘛？',
			success: res => {
				if (res.confirm) {
					let pathData = JSON.parse(JSON.stringify(formData[uploadKey + '_show']))
					pathData.splice(index, 1);
					formData[uploadKey] = pathData.map((item : any) => item.path).join(',');
					// 判定当前页面已进行修改
					isFormModified.value = true;

					setTimeout(() => {
						next();
					}, 300);
				}
			}
		});
	};

	let BoxInfoCallBack = reactive({
		num: 3,
		height: 100
	});
	// 定义文件上传的IP
	let uploadFile_action = mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + '/FileData/UploadSignleFile';
	// 文件上传-上传成功事件
	function onSuccess(data : any, uploadKey : any) {

		let path = mainStore.getReadyStaticUrl(data.data);

		formData[uploadKey + '_show'].push({
			path: path
		});

		let PathData = formData[uploadKey + '_show'].map((item : any) => {
			return item.path
		});
		formData[uploadKey] = PathData.join(',');

		// 判定当前页面已进行修改
		isFormModified.value = true;
	}

	let routes = getCurrentPages(); //当前页面栈
	let routePageCurrent = routes.length;
	//详情页对象名称
	let menuDetailObj = reactive<any>({})
	Object.assign(menuDetailObj, uni.$utils.deepClone(inventoryStore.MenuDetail));
	const {
		id, // 草稿主键ID
		// detailName,
		// keyName,
		// keyValue,
		// detailTitle,
		dataInfo: {
			titleColName,
			showColumnsInfo,
			tagColumnsInfo,
			// childListData = [], // 给待办用的
			// waitKeyName = "", // 给待办用的
		}
	} = menuDetailObj;

	// 设置基础数据信息
	let detailName = ref("");
	let keyName = ref("");
	let keyValue = ref("");
	let titleName = ref("");
	let mainTitle = ref("");
	let mainForm = ref([]);
	let tagForm = ref([]);
	let childListData = ref([]);
	let waitKeyName = ref("");


	detailName.value = menuDetailObj.detailName;
	keyName.value = menuDetailObj.keyName;
	keyValue.value = menuDetailObj.keyValue;
	titleName.value = menuDetailObj.detailTitle.replace('列表', '') + '编辑';
	mainTitle.value = menuDetailObj.dataInfo.titleColName;
	tagForm.value = menuDetailObj.dataInfo.tagColumnsInfo;
	childListData.value = menuDetailObj.dataInfo.childListData || [];
	waitKeyName.value = menuDetailObj.dataInfo.waitKeyName;


	// 获取用户信息，定义本地数据库表名
	let UserInfo = userStore.UserInfo;
	// 设置本地数据库表名
	let tableKeyName = 'appAccount_' + UserInfo.Business + '_' + UserInfo.UserID;
	// 开启数据库
	// openSQL();

	let showMLoading = ref(false);
	let enabledSubmitBtn = ref(true);
	let APPRoleCol = ref([]);
	let globalData = reactive<any>({});
	let physicalTableName = ref("");
	let isUpdate = ref(false);
	let isShowComApproval = ref(false);
	// 审批ID
	let ApprovalID = ref<any>(null);
	let isCurApproval = ref(false);
	let ApprovalSort = ref<any>(null);


	async function initConfig(objName ?: string, callBack ?: () => void) {
		showMLoading.value = true;
		enabledSubmitBtn.value = false;
		isFormModified.value = false; // 初始化时判定当前页面已无修改

		try {
			// 获取主表字段权限
			const roleRet = await permissionStore.getAPPRoleColFunByRoleID({
				request,
				moduleName: detailName.value,
				moduleType: 'formdetail',
			});
			if (roleRet.status === 200) {
				APPRoleCol.value = roleRet.data.ds;
			}
		} catch (error) {
			console.error("获取字段权限失败：", error);
		}

		// 获取表单配置
		const ret = await requestByUrl({
			config: { baseURL: "/AppFormDetail/GetDataByName" },
			url: '',
			method: 'POST',
			data: { objName },
		});
		if (ret.status !== 200) return;

		Object.assign(globalData, uni.$utils.deepClone(ret.data));

		// 没有配置物理表，直接返回
		if (!(ret.data.ds.length && ret.data.ds[0].hasOwnProperty("physicalTableName"))) {
			showMLoading.value = false;
			return layer.alert(`${objName}未配置，请在电脑客户端查看`, () => goBack());
		}
		physicalTableName.value = ret.data.ds[0].physicalTableName;

		// 是否是更新模式
		if (keyName.value && keyValue.value) {
			await handleUpdateMode(ret, callBack);
		} else {

			handleCreateMode(ret);
		}
	}

	/**
	 * 更新模式：编辑已有数据
	 */
	async function handleUpdateMode(ret : any, callBack ?: () => void) {
		isUpdate.value = true;

		const row = await requestByUrl({
			config: { baseURL: "/SQLData/GetTableByKeyId" },
			url: '',
			method: 'POST',
			data: {
				physicalTableName: physicalTableName.value,
				keyName: keyName.value,
				keyValue: keyValue.value,
			},
		});
		if (row.status !== 200) {
			showMLoading.value = false;
			return layer.alert('未找到单据数据，点击确定返回', () => goBack());
		}

		// 填充表单数据
		const result = row.data.ds[0];
		Object.assign(formData, uni.$utils.deepClone(result), {
			P_UserID: UserInfo.UserID || '',
			P_UserName: UserInfo.UserName || '',
			P_UserCode: UserInfo.UserCode || ''
		});

		// 审批配置
		let approvalConfig1 = { isEnableApproval: false };
		if (!uni.$utils.isEmpty(ret.data.ds[0].approvalConfig)) {
			const parsed = JSON.parse(ret.data.ds[0].approvalConfig);
			if (parsed.hasOwnProperty("isEnableApproval")) {
				approvalConfig1 = uni.$utils.deepClone(parsed);
			}
		}

		// 表单配置
		tableConfig({
			childFormList: JSON.parse(ret.data.ds[0].childFormsConfig),
			formDesign: JSON.parse(ret.data.ds[0].formDesignConfig),
			physicalTableName: ret.data.ds[0].physicalTableName,
			workList: JSON.parse(ret.data.ds[0].worksConfig),
			crudList: JSON.parse(ret.data.ds[0].crudConfig),
			importConfig: JSON.parse(ret.data.ds[0].importConfig),
			scanConfig: ret.data.ds[0].scanConfig,
			printConfig: ret.data.ds[0].printConfig,
			onReadyCallBack: ret.data.ds[0].onReadyCallBack,
			approvalConfig: approvalConfig1,
		});

		callBack && callBack();
		// 表单菜单项处理
		addFormMenus(ret);

		// 查询是否存在审批流
		await checkApprovalFlow();
	}

	/**
	 * 新建模式：初始化表单
	 */
	function handleCreateMode(ret : any) {
		isUpdate.value = false;
		// 设置默认值
		if (ret.data.ds[0].formDesignConfig) {
			const newFormData : Record<string, any> = reactive({});
			const designControls = JSON.parse(ret.data.ds[0].formDesignConfig);

			designControls.forEach((ctrl : any) => {
				const defaultValue = ctrl.baseProperty.defaultValue;
				if (defaultValue && defaultValue.indexOf('@') < 0) {
					newFormData[ctrl.baseProperty.controlName] = getSYDefaultValue(defaultValue);
				} else if (defaultValue && defaultValue.indexOf('@') >= 0) {
					const userInfo = getSYDefaultValue(defaultValue);
					newFormData[ctrl.baseProperty.controlName] = userInfo.P_UserID;
					newFormData[ctrl.baseProperty.controlName + '_show'] = userInfo.P_UserName;
				} else {
					newFormData[ctrl.baseProperty.controlName] = "";
				}
			});

			Object.assign(formData, {}, newFormData);

			if (origin.value === 'draft') {
				Object.assign(formData, menuDetailObj.dataInfo.formData);
			} else if (childListData.value.length) {
				formData[waitKeyName.value] = childListData.value[0][waitKeyName.value];
			}
		}

		// 表单配置
		tableConfig({
			childFormList: JSON.parse(ret.data.ds[0].childFormsConfig),
			formDesign: JSON.parse(ret.data.ds[0].formDesignConfig),
			physicalTableName: ret.data.ds[0].physicalTableName,
			workList: JSON.parse(ret.data.ds[0].worksConfig),
			crudList: JSON.parse(ret.data.ds[0].crudConfig),
			importConfig: JSON.parse(ret.data.ds[0].importConfig),
			scanConfig: ret.data.ds[0].scanConfig,
			onReadyCallBack: ret.data.ds[0].onReadyCallBack,
			approvalConfig: { isEnableApproval: false },
		});
	}

	/**
	 * 添加菜单按钮
	 */
	function addFormMenus(ret : any) {
		const menus = formMenus.value;


		if (!uni.$utils.isEmpty(ret.data.ds[0].printConfig)) {
			if (!menus.some((item : any) => item.name === '打印机列表')) {
				menus.push(
					{ name: '打印机列表', value: '', icon: 'list-dot' },
					{ name: '打印', value: '', icon: 'coupon' }
				);
			}
		}
	}

	/**
	 * 查询是否存在审批流
	 */
	async function checkApprovalFlow() {
		const sql = `select * from Ba_Audit where isnull(History,0)=0 and SourceTable='${physicalTableName.value}' 
		             and SourceID=${keyValue.value} order by APFlowID desc`;

		const ret1 = await requestByUrl({
			config: { baseURL: "/SQLData/QuerySql" },
			url: '',
			method: 'POST',
			data: { sql },
		});

		if (ret1.data.ds.length > 0) {
			isShowComApproval.value = true;
			ApprovalID.value = ret1.data.ds[0].APFlowID;

			// 是否可以审批
			request({
				url: 'WhetherItCanBeApproved',
				method: 'POST',
				data: {
					P_TableName: physicalTableName.value,
					P_PKValue: keyValue.value,
				},
				success(row : any) {
					if (row.data.ds[0].ISSP == 1) {
						isCurApproval.value = true;
						ApprovalSort.value = row.data.ds[0].ApprovalSort;
					} else {
						isCurApproval.value = false;
						if (origin.value === "approveWaitList") {
							openNextPage();
						}
					}
				},
			});
		}
	};


	// 整合后的系统默认值获取方法
	// 定义日期间隔类型
	type DateInterval = 's' | 'n' | 'h' | 'd' | 'w' | 'q' | 'm' | 'y';
	const getSYDefaultValue = (funcName : string) : any => {
		// 处理日期相关函数
		if (funcName.includes("getdate()")) {
			// 基础日期对象
			let date = new Date();

			// 处理日期加减
			if (funcName !== "getdate()") {
				// 匹配日期添加模式
				const match = funcName.match(/getdate\(\)\.DateAdd\('([a-z])',\s*(-?\d+)\)/i);
				if (match && match.length === 3) {
					const interval = match[1].toLowerCase() as DateInterval;
					const number = parseInt(match[2], 10);

					// 根据间隔类型计算新日期
					switch (interval) {
						case 's':
							date = new Date(date.getTime() + (1000 * number));
							break;
						case 'n':
							date = new Date(date.getTime() + (60000 * number));
							break;
						case 'h':
							date = new Date(date.getTime() + (3600000 * number));
							break;
						case 'd':
							date = new Date(date.getTime() + (86400000 * number));
							break;
						case 'w':
							date = new Date(date.getTime() + ((86400000 * 7) * number));
							break;
						case 'q':
							date = new Date(date.getFullYear(), date.getMonth() + number * 3, date.getDate(),
								date.getHours(), date.getMinutes(), date.getSeconds());
							break;
						case 'm':
							date = new Date(date.getFullYear(), date.getMonth() + number, date.getDate(),
								date.getHours(), date.getMinutes(), date.getSeconds());
							break;
						case 'y':
							date = new Date(date.getFullYear() + number, date.getMonth(), date.getDate(),
								date.getHours(), date.getMinutes(), date.getSeconds());
							break;
					}
				}
			}

			// 格式化日期为字符串
			const seperator1 = "-";
			const seperator2 = ":";
			const month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1;
			const strDate = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
			const hours = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours();
			const minutes = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes();
			const seconds = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();

			return `${date.getFullYear()}${seperator1}${month}${seperator1}${strDate} ${hours}${seperator2}${minutes}${seperator2}${seconds}`;
		}

		// 处理Cookie相关
		else if (funcName.includes("$.cookie")) {
			const match = funcName.match(/\$\.cookie\('([^']+)'\)/);
			if (match && match.length === 2) {
				const cookieName = match[1];
				const cookies = document.cookie.split(';');
				for (const cookie of cookies) {
					const [name, value] = cookie.trim().split('=');
					if (name === cookieName) {
						return decodeURIComponent(value);
					}
				}
			}
			return null;
		}

		// 处理自定义函数
		else if (funcName.includes('func:')) {
			try {
				const funcBody = funcName.split(':')[1];
				// const func = new Function(`return (${funcBody})()`);

				const func = run(`return (${funcBody})()`, {
					// 注入UniApp环境的API（如uni对象）
					uni: uni,
					formData: formData,
					post,
					layer
				})

				return func();
			} catch (error) {
				console.error('Error executing custom function:', error);
				return null;
			}
		}

		// 处理用户信息参数
		else if (funcName.includes("@")) {
			if (funcName == '@P_UserID') {
				return {
					P_UserID: UserInfo.UserID,
					P_UserName: UserInfo.UserName
				}
			} else if (funcName == '@EmplID') {
				return {
					P_UserID: UserInfo.EmplID,
					P_UserName: UserInfo.EmplName
				}
			}
		}

		// 处理localStorage
		else if (funcName.includes('localStorage.getItem')) {
			const match = funcName.match(/localStorage\.getItem\('([^']+)'\)/);
			if (match && match.length === 2) {
				return localStorage.getItem(match[1]) || null;
			}
			return null;
		}

		// 默认返回原字符串
		else {
			return funcName;
		}
	};
	// 向列表页发起切换下一条数据的指令
	function openNextPage() {
		if (origin.value == "approveWaitList") {
			uni.$emit('switch-to-next-item');
		}
	}

	let workList = ref<any>([]);
	let crudList = ref<any>([]);
	let approvalConfig = reactive<any>({});
	let MoreSheetList = ref<any>([]);
	let showMoreSheet = ref(false);
	function selfWorkHandler(work : any) {
		if (!enabledSubmitBtn.value) {
			return;
		} else {
			enabledSubmitBtn.value = false;
			if (work.script.includes('buttonCoreTask(')) {
				selfWorkTaskHandler(
					work.script,
					'formData',
					{
						uni,
						formData,
						importEvent,
						work,
					}
				);
				return;
			}

			function task1() {
				return new Promise((resolve : any, reject : any) => {
					try {

						let script = work.script.replace(/vm\./g, '');
						script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');
						// eval(script);
						// new Function('formData', script)(formData);
						run(`
						${script}
						`, {
							// 注入UniApp环境的API（如uni对象）
							uni: uni,
							formData: formData,
							importEvent: importEvent,
							work,
							post,
							layer: uni.$utils.layer,
							refreshPage
						})

						resolve();

					} catch (error) {
						reject(error);
					}
				});
			}

			task1().then(() => {
				enabledSubmitBtn.value = true;
				uni.$utils.hideLoading();
			}).catch((error) => {
				enabledSubmitBtn.value = true;
				uni.$utils.hideLoading();
				uni.showToast({
					title: error,
					icon: 'error'
				})
				console.error('An error occurred:', error);
			});
		}
	};
	function closeSheetBtn() {
		showMoreSheet.value = false;
	}
	// 点击更多按钮 --- 业务按钮
	function openMoreSheet() {
		if (!enabledSubmitBtn.value) {
			return;
		}

		let benArr = MoreSheetList.value.map((item : any) => {
			return item.name
		})

		uni.showActionSheet({
			itemList: benArr,
			success: function (res) {

				selfWorkHandler(MoreSheetList.value[res.tapIndex]);
			},
			fail: function (res) {

				enabledSubmitBtn.value = true;
			}
		});

	}

	let onReadyCallBack = ref<any>(null)
	let scanConfig = ref<any>(null)
	let printConfig = ref<any>(null)
	let importConfig = ref<any>([]);
	let childFormList = ref<any>([]);
	// 子表数据映射
	function childApproveShowFun(data : any) {
		try {
			if (!uni.$utils.isEmpty(data)) { // 判断是否存在子表数据
				const appRoleColChildMap = APPRoleColChildList.value;
				data.forEach((item : any) => {
					item.colInfo.forEach((row : any) => {
						const colName = row.colName; // 缓存colName，减少访问次数
						const typeInfo = appRoleColChildMap.get(colName); // 子表权限隐藏字段处理
						if (typeInfo) {
							// 调整字段配置数据
							const isViewRole = typeInfo.IsViewRole;
							const isEditRole = typeInfo.IsEditRole;
							row.isHidden = !isViewRole;
							row.isReadOnly = !isEditRole;
							// row.isReadOnly = !isViewRole && !isEditRole;
						}
					});
				});
			};

		} catch (error) {
			//TODO handle the exception
		}

		return data || [];
	};
	let delSwiper = ref<any>(null);
	function delRow(childForm : any, delRecord : any) {
		uni.showModal({
			title: '提示',
			content: '是否删除此行？',
			success: function (res : any) {
				if (res.confirm) {
					//不存在在新增中
					if (childForm.crud.create.filter(function (item : any) {
						return item.guid == delRecord.guid
					}).length == 0 && childForm.crud.update.filter(function (item : any) {
						return item.guid == delRecord.guid
					}).length == 0) {
						childForm.crud.delete.push(delRecord);
					}
					//存在在更新中
					else if (childForm.crud.update.filter(function (item : any) {
						return item.guid == delRecord.guid
					}).length > 0) {
						childForm.crud.update = childForm.crud.update.filter(function (item : any) {
							return item.guid != delRecord.guid
						});
						childForm.crud.delete.push(delRecord);
					} else if (childForm.crud.create.filter(function (item : any) {
						return item.guid == delRecord.guid
					}).length > 0) {
						childForm.crud.create = childForm.crud.create.filter(function (item : any) {
							return item.guid != delRecord.guid
						});
					}
					//删除表格里的数据
					childForm.tableData = childForm.tableData.filter(function (item : any) {
						return item.guid != delRecord.guid;
					});
					for (let i = 0; i < childForm.tableData.length; i++) {
						childForm.tableData[i].objNo = (i + 1).toString();
						if (!childForm.tableData[i].guid) {
							childForm.tableData[i].guid = guid();
						}
					}
					delSwiper.value.forEach((item : any) => item.closeHandler(true));

				} else if (res.cancel) { }
			}
		});
	};

	// 被打开的索引数据
	let childOpenIndex = ref(0);
	let editValues = reactive<{
		[key : string] : any
	}>({});
	let editFrame = reactive<any>({});
	let showEditWin = ref(false)
	interface popupInstance {
		open : () => void;
		close : () => void;
	}
	let EditWinPopup = ref<popupInstance | any>(null);
	//打开编辑窗口
	function openEditWin(editObj : any, childForm : any, ind : any) {
		// 记录打开的所有
		childOpenIndex.value = ind;

		// 获取文件上传字段
		let filterData = childForm.columns.filter((item : any) => {
			return item.colName.indexOf("FilePath") !== -1
		})
		if (filterData.length) {

			// 处理文件上传字段操作
			filterData.forEach((item : any) => {
				if (item.colName.indexOf("FilePath") !== -1) {
					let arrData = [];
					if (!uni.$utils.isEmpty(editObj[item.colName])) {
						let splitData = editObj[item.colName].split(',');

						arrData = splitData.map((item : any, index ?: any, originalArray ?: any) => {


							let mapItem = mainStore.getReadyStaticUrl(item);

							return {
								path: mapItem
							};
						});
					};
					// 增加 _show 字段存储数组数据
					editObj[item.colName + '_show'] = arrData;
				}
			})

		};





		Object.assign(editValues, uni.$utils.deepClone(editObj))
		Object.assign(editFrame, uni.$utils.deepClone(childForm))
		showEditWin.value = true;
		EditWinPopup.value.open();
	};
	function closeEditWin() {

		// 
		childFormList.value[tabCurrent.value].tableData[childOpenIndex.value] = uni.$utils.deepClone(editValues);

		// 给被打开的数组数据赋值
		updateRow(editValues);
		showEditWin.value = false;
		EditWinPopup.value.close();
		refreshEditValueCol();


		Object.keys(editValues).forEach(key => {
			delete editValues[key];
		});
		Object.assign(editValues, {});
		Object.keys(editFrame).forEach(key => {
			delete editFrame[key];
		});
		Object.assign(editFrame, {});
	};
	// 定义类型接口，增强类型安全
	interface SelDetail {
		type : number;
		dataSource : string;
		hiddenValue ?: string;
		sqlDataSource ?: any[];
	}



	/**
	 * 刷新编辑值列，处理下拉框数据加载
	 * @param childObj1 子对象数据，包含列定义和表格数据
	 */
	function refreshEditValueCol(childObj1 ?: any) {
		// 检查childObj是否为空（假设childObj是外部变量）
		if (uni.$utils.isEmpty(childObj1)) {
			refreshChildCol(childObj.value); // 假设refreshChildCol是已定义的函数
			return;
		} else {
			for (let i = 0; i < childObj1.columns.length; i++) {
				//下拉框数据加载
				// 类型小于3的下拉框数据加载
				if (childObj1.columns[i].colType == 2 && childObj1.columns[i].selDetail.type < 3) {
					let sql = childObj1.columns[i].selDetail.dataSource;
					let selDetailObj = childObj1.columns[i].selDetail;
					changeDataAjax(childObj1.columns[i].selDetail.dataSource,
						"1=1",
						function (data : any, requestObj : any) {

							requestObj.sqlDataSource = data;
						},
						selDetailObj);
				}
				// 类型等于3的下拉框数据加载
				else if (childObj1.columns[i].colType == 2 && childObj1.columns[i].selDetail.type == 3) {
					let valueList = [];
					if (editValues[childObj1.columns[i].colName]) {
						for (let k = 0; k < editValues[childObj1.columns[i].colName].toString().split(',').length; k++) {
							valueList.push("'" + editValues[childObj1.columns[i].colName].toString().split(',')[k] + "'");
						}
					}
					//加上原有表格内的当前数据集合
					childObj1.tableData.forEach(function (tItem : any) {
						if (tItem[childObj1.columns[i].colName] != null && tItem[childObj1.columns[i].colName] != undefined && tItem[childObj1.columns[i].colName] != 'undefined' && tItem[childObj1.columns[i].colName] != 'null') {
							for (let k = 0; k < (tItem[childObj1.columns[i].colName].toString()).split(',').length; k++) {
								valueList.push("'" + (tItem[childObj1.columns[i].colName].toString()).split(',')[k] + "'");
							}
						}
					});

					if (valueList.length > 0) {
						var selDetailObj = childObj1.columns[i].selDetail;
						changeDataAjax(childObj1.columns[i].selDetail.dataSource,
							childObj1.columns[i].selDetail.hiddenValue + " in (" + valueList.join(',') + ") ",
							function (data : any, requestObj : any) {
								requestObj.sqlDataSource = data;
							},
							selDetailObj);
					} else {
						childObj1.columns[i].selDetail.sqlDataSource = [];
					}


				}
			}



		};
	}

	//更新行
	function updateRow(modifyRecord1 : any) {
		let modifyRecord = uni.$utils.deepClone(modifyRecord1);
		// 判定当前页面已进行修改
		isFormModified.value = true;

		let filterDataByCrete = childFormList.value[tabCurrent.value].crud.create.filter(function (item : any) {
			return item.guid == modifyRecord.guid
		});

		//不存在在新增中
		if (filterDataByCrete.length == 0) {
			let filterDataByUpdate = childFormList.value[tabCurrent.value].crud.update.filter(function (item : any) {
				return item.guid == modifyRecord.guid
			})
			//同时也不存在在更新中
			if (filterDataByUpdate.length == 0) {
				childFormList.value[tabCurrent.value].crud.update.push(modifyRecord)
			} else {
				for (let i = 0; i < childFormList.value[tabCurrent.value].crud.update.length; i++) {
					if (childFormList.value[tabCurrent.value].crud.update[i].guid == modifyRecord.guid) {
						childFormList.value[tabCurrent.value].crud.update[i] = uni.$utils.deepClone(modifyRecord);
					}
				}
			}
		} else {
			for (let i = 0; i < childFormList.value[tabCurrent.value].crud.create.length; i++) {
				if (childFormList.value[tabCurrent.value].crud.create[i].guid == modifyRecord.guid) {
					childFormList.value[tabCurrent.value].crud.create[i] = uni.$utils.deepClone(modifyRecord);
				}
			};
		}
	};
	//显示下拉数据源中的真实数据
	function showActualValue(value : any, colObject ?: any, originValue ?: any) {
		// 
		if (colObject.selDetail.sqlDataSource) {
			let curObject = colObject.selDetail.sqlDataSource.filter(function (item : any) {
				return item[colObject.selDetail.hiddenValue] == value
			});
			// 
			if (curObject.length > 0) {
				return curObject[0][colObject.selDetail.displayValue];
			} else if (originValue) {
				return originValue;
			} else {
				return '';
			}
		} else {
			return '';
		}
	};
	// 处理关于子表文件上传的显示
	function showFileTheNumFun(data : any) {
		if (uni.$utils.isEmpty(data)) {
			return "";
		}
		return '+' + data.split(',').length;
	};
	//子表渲染条件
	function btn_showConditionByChild(btn : any) {
		try {
			let result = ref(true);
			let showScript = "";
			//业务按钮
			showScript = btn.show;
			if (showScript) {
				let script = showScript.replace(/vm\./g, '');
				script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');

				const runInfo = `${"result.value=(" + script + ")"}`
				run(runInfo, {
					// 注入UniApp环境的API（如uni对象）
					uni: uni,
					formData: formData,
					approvalConfig,
					post,
					result,
					layer
				});
			}
			return result.value;
		} catch (e) {
			return false;
		}
	};
	let currentRow = reactive<any>({})
	//自定义子表业务按钮事件
	function selfChildWorkHandler(work : any, currentRow ?: any) {
		if (!enabledSubmitBtn.value) {
			return;
		} else {
			enabledSubmitBtn.value = false;

			if (work.script.includes('buttonCoreTask(')) {
				selfWorkTaskHandler(
					work.script,
					'currentRow',
					{
						uni,
						formData,
						importEvent,
						currentRow,
						work,
					}
				);
				return;
			}

			let script = work.script.replace(/vm\./g, '');
			script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'currentRow$1');
			run(script, {
				// 注入UniApp环境的API（如uni对象）
				uni: uni,
				formData: formData,
				importEvent: importEvent,
				currentRow,
				post,
				work,
				layer
			})
		}
	};
	let curDateObj2 = ref<any>({})
	let DateFormatType2 = ref('date');
	let curDat2 = ref("")
	function onDatePickerConfirm2(valueData : any) {
		let value = valueData.value + '';
		if (value && !isNaN(Number(value))) {
			let dateFormat = 'yyyy-MM-dd';
			let dateDown = uni.$utils.dateFormat(new Date(Number(value)), dateFormat);
			editValues[curDateObj2.value.colName] = dateDown;
		} else if (!value) {
			editValues[curDateObj2.value.colName] = "";
		};
		showDatePicker2.value = false;
		curDateObj2.value = {};
		curDat2.value = '';
	};
	function closeByPicker2() {
		showDatePicker2.value = false;
		curDate2.value = '';
	};
	let curDate2 = ref<any>(null);
	let showDatePicker2 = ref(false);
	function clickDatePicker2(row : any) {


		if (row.isReadOnly) {
			return false;
		} else {
			curDateObj2.value = row;
			let theDate = new Date();
			if (!uni.$utils.isEmpty(editValues[row.colName])) {
				theDate = new Date(editValues[row.colName]);
			}
			let dateFormat = 'yyyy-MM-dd';


			// 点击时间选项时，确认日期控件格式
			let DateFormatType = uni.$utils.getDateFormatType(dateFormat);
			DateFormatType2.value = DateFormatType;
			// let dateDown = uni.$utils.dateFormat(theDate, dateFormat);
			// 
			curDate2.value = Number(theDate);
			showDatePicker2.value = true;
		}
	};

	// 下拉控件
	let windowSelectType = ref(1);
	// let curSelectWindowObj = reactive<any>({});
	let curSelectWindowObj = ref<any>({});
	function openBaseScreen(row : any) {
		console.log(row);
		if (row.isReadOnly) return;
		windowSelectType.value = 1;
		// Object.assign(curSelectWindowObj, {}, row);
		curSelectWindowObj.value = row;
		if (row.baseProperty.isReadOnly) {
			return false;
		} else {
			let formSQL = row.controlProperty.select.formSQL || '';

			//带有@父节点标识的字段
			if (formSQL.indexOf('@') >= 0) {
				for (let name in formData) {
					let repalceValue = "'" + formData[name] + "'";
					// eval("formSQL = formSQL.replace(/@" + name + "/g, repalceValue)");
					// new Function("formSQL = formSQL.replace(/@" + name + "/g, repalceValue)")();

					const regex = new RegExp(`@@${name}`, 'g');
					formSQL = formSQL.replace(regex, repalceValue);
				}
			}

			// 

			let obj = reactive<any>({
				chooseType: row.controlProperty.select.chooseType,
				allowClear: true,
				showSearch: true,
				searchKey: row.controlProperty.select.displayValue,
				serverSearch: true,
				displayValue: row.controlProperty.select.displayValue,
				hiddenValue: row.controlProperty.select.hiddenValue,
				parentValue: row.controlProperty.select.parentValue,
				isPaging: true,
				sql: row.controlProperty.select.dataSource,
				name: row.baseProperty.labelName,
				colName: row.baseProperty.controlName,
				param: {},
				treeObj: {
					treeDataSource: row.controlProperty.select.treeDataSource,
					treeDisplayValue: row.controlProperty.select.treeDisplayValue,
					treeHiddenValue: row.controlProperty.select.treeHiddenValue,
					treeParentValues: row.controlProperty.select.treeParentValues,
				},
				filterSQL: row.controlProperty.select.filterSQL,
				formSQL: formSQL
			})
			// 
			obj.param = JSON.parse(JSON.stringify(formData));
			obj.param[row.controlProperty.select.displayValue] = "";
			mainStore.SelectPickerSetting = obj;


			uni.navigateTo({
				// url: '/commonPage/Tool/selectPicker'
				url: '/commonPage/Tool/selectPicker' + '?pickerListen=' + selectPicker_formEditCurrent.value
			})
		}
	};
	// let curSelectWindowObj2 = reactive<any>({});
	let curSelectWindowObj2 = ref<any>({});
	function openBaseScreen2(row : any) {
		if (row.isReadOnly) return;

		windowSelectType.value = 2;

		// Object.assign(curSelectWindowObj2, {}, row);
		curSelectWindowObj2.value = row;

		if (row.isReadOnly) {
			return false;
		} else {
			let formSQL = row.selDetail.formSQL || "";
			//带有@@父节点标识的字段
			if (formSQL.indexOf('@@') >= 0) {
				for (let name in formData) {
					let repalceValue = "'" + formData[name] + "'";

					// eval("formSQL = formSQL.replace(/@@" + name + "/g, repalceValue)");

					const regex = new RegExp(`@@${name}`, 'g');
					formSQL = formSQL.replace(regex, repalceValue);

				}
			};

			//带有@子节点标识的字段
			if (formSQL.indexOf('@') >= 0) {
				for (let name in editValues) {
					let repalceValue = "'" + editValues[name] + "'";

					// eval("formSQL = formSQL.replace(/@" + name + "/g, repalceValue)");
					// new Function("formSQL = formSQL.replace(/@" + name + "/g, repalceValue)")();

					const regex = new RegExp(`@@${name}`, 'g');
					formSQL = formSQL.replace(regex, repalceValue);
				}
			};

			let obj = reactive<any>({
				chooseType: row.selDetail.chooseType,
				allowClear: true,
				showSearch: true,
				searchKey: row.selDetail.displayValue,
				serverSearch: true,
				displayValue: row.selDetail.displayValue,
				hiddenValue: row.selDetail.hiddenValue,
				parentValue: row.selDetail.parentValue,
				isPaging: true,
				sql: row.selDetail.dataSource,
				name: row.colDesc,
				colName: row.colName,
				param: {},
				treeObj: {
					treeDataSource: row.selDetail.treeDataSource,
					treeDisplayValue: row.selDetail.treeDisplayValue,
					treeHiddenValue: row.selDetail.treeHiddenValue,
					treeParentValues: row.selDetail.treeParentValues,
				},
				filterSQL: row.selDetail.filterSQL,
				formSQL: formSQL
			})
			obj.param = JSON.parse(JSON.stringify(editValues));
			obj.param.colInfo = "";
			obj.param[row.selDetail.displayValue] = "";

			mainStore.SelectPickerSetting = obj;


			uni.navigateTo({
				url: '/commonPage/Tool/selectPicker' + '?pickerListen=' + selectPicker_formEditCurrent.value
			})
		}
	};
	// 下拉选监听器
	const selectPicker_formEditCurrent = computed(() => {
		let routes = getCurrentPages(); //当前页面栈
		return "selectPicker_formEdit" + routes.length;
	});
	function itemDataChange(formCol : any, curRow ?: any, childForm ?: any, returnValue : any = {}) {
		// 判断是否是异步操作
		let isAsyncOperation = false;
		// 判定当前页面已进行修改
		isFormModified.value = true;

		// 如果是异步的，需要在脚本中，将isAsyncOperation设为true，并在脚本中执行子表刷新方法
		//更新修改行数据
		if (formCol.colCallBack) {
			let script = formCol.colCallBack.replace(/vm\./g, '');
			// 只匹配作为属性访问的 [''] 或 [""] 形式，并在前面添加 curRow
			script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'editValues$1');
			// script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'curRow$1');

			run(script, {
				// 注入UniApp环境的API（如uni对象）
				uni: uni,
				formData: formData,
				curRow,
				editValues,
				returnValue,
				post,
				refreshEditValueCol,
				editFrame,
				layer
			})
		}
		if (formCol.colChange) {
			let script = formCol.colChange.replace(/vm\./g, '');
			script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'editValues$1');

			run(script, {
				// 注入UniApp环境的API（如uni对象）
				uni: uni,
				formData: formData,
				curRow,
				editValues,
				returnValue,
				post,
				refreshEditValueCol,
				editFrame,
				layer
			})
		}
		//刷新子表
		// 如果是同步操作，则自动进行下方方法
		if (!isAsyncOperation) {

			refreshEditValueCol(childForm);

		}
	};
	// 文件上传-删除指定数据事件
	function beforeDeleteByChild({ fileToDelete,
		uploadKey } : any, index : any, next : any) {
		uni.showModal({
			title: '提示信息',
			content: '确定要删除这个文件嘛？',
			success: res => {
				if (res.confirm) {
					let pathData = JSON.parse(JSON.stringify(editValues[uploadKey + '_show']))
					pathData.splice(index, 1);
					editValues[uploadKey] = pathData.map((item : any) => item.path).join(',');

					// 判定当前页面已进行修改
					isFormModified.value = true;
					setTimeout(() => {
						next();
					}, 300);
				}
			}
		});
	};
	// 文件上传-上传成功事件
	function onSuccessByChild(data : any, uploadKey ?: any) {
		let path = mainStore.getReadyStaticUrl(data.data);

		editValues[uploadKey + '_show'].push({
			path: path
		})
		let PathData = editValues[uploadKey + '_show'].map((item : any) => {
			return item.path
		});

		editValues[uploadKey] = PathData.join(',');

		refreshEditValueCol(editFrame);
		// 判定当前页面已进行修改
		isFormModified.value = true;
	}

	let TabList = ref<any>([])
	let deleteOper = [{
		icon: 'trash-fill',
		style: {
			backgroundColor: '#ff0000',
			color: '#fff'
		}
	}]


	const startsWithHttp = (url : string) =>
		url.startsWith('http://') || url.startsWith('https://');

	async function tableConfig(options : any) {

		if (options.childFormList == null) {
			options.childFormList = [];
		}
		workList.value = options.workList;
		crudList.value = options.crudList;
		Object.assign(approvalConfig, options.approvalConfig);

		// 调整业务按钮
		// 存在业务按钮时
		if (workList.value.length) {
			// 从 Vuex 存储中获取无权限配置
			const permissionDeniedFunctions = permissionStore.filterUnPermissionConfig;

			// 将业务按钮的条件进行eval执行
			const buttonConditions = await btn_showCondition1(workList.value);

			// 提取所有无权限的函数名到一个 Set 中
			const funNamesSet = new Set(permissionDeniedFunctions.map((item : any) => item.FunName));

			// 筛选按钮条件数组，只保留那些 name 不在无权限函数名集合中的元素
			const filteredButtons = buttonConditions.filter((item : any) => !funNamesSet.has(item.name));

			// 映射数据并更新
			MoreSheetList.value = filteredButtons.map((item : any) => ({
				...item,
				title: item.name
			}));

		};

		onReadyCallBack.value = options.onReadyCallBack;
		scanConfig.value = options.scanConfig;
		printConfig.value = options.printConfig;
		importConfig.value = options.importConfig;
		childFormList.value = options.childFormList || [];
		TabList.value = [];



		for (let i = 0; i < childFormList.value.length; i++) {

			TabList.value.push(childFormList.value[i]);


			//基础数据增删改查列表
			childFormList.value[i].crud = {
				create: [],
				update: [],
				delete: []
			};
			childFormList.value[i].fixedValues = {}
			await childPageInit(childFormList.value[i]);
		}


		if (TabList.value.length) {
			clickTabItem({
				index: 0
			})
		};

		for (let i = 0; i < options.formDesign.length; i++) {
			//日期控件，格式化内容
			if (options.formDesign[i].baseProperty.controlType == 'datepicker') {
				const control = options.formDesign[i];
				const controlName = control.baseProperty.controlName;
				const dateFormat = control.controlProperty.date?.type || "yyyy-MM-dd";

				formData[controlName] = formatterDate(formData[controlName], dateFormat);

			}
			if (options.formDesign[i].baseProperty.controlType == "select") {

				//下拉框数据加载
				if (options.formDesign[i].controlProperty.select.type < 3) {
					let sql = options.formDesign[i].controlProperty.select.dataSource;

					let formDesignObj = options.formDesign[i];

					dealSelectDatasource(sql, formDesignObj);
				}
				else if (options.formDesign[i].controlProperty.select.type == 3) {

					if (options.formDesign[i].controlProperty.select.chooseType == 1) {
						let valueList = [];
						if (formData[options.formDesign[i].baseProperty.controlName] != undefined &&
							formData[options.formDesign[i].baseProperty.controlName] !== "") {
							valueList.push("'" + formData[options.formDesign[i].baseProperty.controlName] + "'");
						}
						let sql = "select * from (" + options.formDesign[i].controlProperty.select
							.dataSource +
							")t";

						if (valueList.length > 0) {
							sql += " where " + options.formDesign[i].controlProperty.select
								.hiddenValue + " in (" +
								valueList.join(',') + ") ";
							let formDesignObj = options.formDesign[i];

							dealSelectDatasourceByTree(sql, formDesignObj);
						}
						else {
							options.formDesign[i].controlProperty.select["sqlDataSource"] = [];
							options.formDesign[i].controlProperty.select["originDataSource"] = [];
							options.formDesign[i].controlProperty.select["actualName"] = "";
							formData[options.formDesign[i].baseProperty.controlName + '_show'] = '';

						}
					}
					else {
						let valueList = "";
						if (formData[options.formDesign[i].baseProperty.controlName] != undefined &&
							formData[options.formDesign[i].baseProperty.controlName] !== "") {
							let valueArray = [];
							valueArray = formData[options.formDesign[i].baseProperty.controlName]
								.toString()
								.split(',');
							for (let q = 0; q < valueArray.length; q++) {
								valueArray[q] = "'" + valueArray[q] + "'";
							}
							valueList = valueArray.join(',');
						}
						let formDesignObj = options.formDesign[i];
						let sql = "select * from (" + options.formDesign[i].controlProperty.select
							.dataSource +
							")t";
						if (valueList) {
							sql += " where " + options.formDesign[i].controlProperty.select
								.hiddenValue + " in (" +
								valueList + ") ";
							dealSelectDatasourceByTree(sql, formDesignObj);
						} else {
							options.formDesign[i].controlProperty.select["actualName"] = "";
							options.formDesign[i].controlProperty.select["sqlDataSource"] = [];
							options.formDesign[i].controlProperty.select["originDataSource"] = [];
							formData[options.formDesign[i].baseProperty.controlName + '_show'] = ''
						}
					}
				}
			};
		}


		if (origin.value == 'draft') { // 来源-草稿箱
			if (!isUpdate.value) {

				let selections = menuDetailObj.MenuDetail.dataInfo.childListData;
				let childFormDatas : any = [];

				// 
				// 

				childFormList.value.forEach((item : any) => {
					item['columns'] = columns.value;
					// item['tableData'] = selections;

					childFormDatas.push({
						name: item.title,
						frameName: item.name,
						record: selections
					});
				});


				setTimeout(() => {
					//插入子表数据
					childFormDatas.forEach((item : any) => {
						if (item.record.length && JSON.stringify(item) != '{}') {
							//插入子表
							insertImportData(item.frameName, item.record);
						}
					});
				}, 300)

			}


		} else {

			// 加载完成，触发
			if (!uni.$utils.isEmpty(onReadyCallBack.value) && !isUpdate.value) {

				setTimeout(() => {
					// 
					// 先替换特定的vm.columns和vm.childListData
					let script = onReadyCallBack.value
					// .replace(/vm\.columns/g, 'columns.value')
					// .replace(/vm\.childFormList/g, 'childFormList.value')
					// .replace(/vm\.childListData/g, 'childListData.value');

					// 清除其他剩余的vm.前缀
					script = script.replace(/vm\./g, '');
					// 将[]数据替换为formData[]形式
					script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');

					run(`${script}`, {
						// 注入UniApp环境的API（如uni对象）
						uni: uni,
						formData: formData,
						columns: columns.value,
						childFormList: childFormList.value,
						childListData: childListData.value,
						onReadyCallBack: script,
						post,
						layer
					})
				}, 500)
			}
		};


		// 获取文件上传字段
		const filterData = options.formDesign.filter(
			(item : any) => item.baseProperty.controlType == 'fileUpload'
		);
		if (filterData.length) {

			// 处理文件上传字段操作
			filterData.forEach((item : any) => {
				if (item.baseProperty.controlName) {
					let arrData = [];
					if (!uni.$utils.isEmpty(formData[item.baseProperty.controlName])) {
						let splitData = formData[item.baseProperty.controlName].split(',');

						arrData = splitData.map((item : any, index ?: any, originalArray ?: any) => {
							let mapItem = mainStore.getReadyStaticUrl(item);

							return {
								path: mapItem
							};
						});
					};
					// 
					// 增加 _show 字段存储数组数据
					formData[item.baseProperty.controlName + '_show'] = arrData;
				}
			})

		};

		// 处理字段显示问题
		try {

			const aDataMap = new Map(APPRoleCol.value.map((row : any) => [row.ColName, row]));

			options.formDesign.forEach((item : any) => {
				const typeInfo = aDataMap.get(item.baseProperty.controlName);

				if (typeInfo) {
					// 直接使用 typeInfo
					item.baseProperty.controlType = typeInfo.IsViewRole ? item.baseProperty.controlType : 'hidden';
					item.baseProperty.isReadOnly = !typeInfo.IsEditRole;
				}
			});
		} catch (error) {
			//TODO handle the exception
		}

		formDesign.value = options.formDesign.filter((item : any) => item.baseProperty.controlType !== 'hidden');

	};



	function insertImportData(childName : string, importDatas : any) {

		let selectChildren = childFormList.value.filter(function (item : any) {
			return item.name == childName
		});

		if (selectChildren.length > 0) {


			importDatas.forEach((item : any) => {

				let importObj = JSON.parse(JSON.stringify(selectChildren[0].fixedValues))

				Object.assign(importObj, item, {
					P_UserID: UserInfo?.UserID || '',
					P_UserName: UserInfo?.UserName || '',
					P_UserCode: UserInfo?.UserCode || ''
				});
				let connectParams = selectChildren[0].connectParams;
				if (formData[connectParams]) {
					importObj[connectParams] = formData[connectParams];
				}


				if (!('tableData' in selectChildren[0])) {
					selectChildren[0]['tableData'] = [];
				};

				selectChildren[0]['tableData'].push(importObj);
				selectChildren[0].crud.create.push(importObj);

			})


			if (uni.$utils.isEmpty(selectChildren[0]['columns'])) {
				selectChildren[0]['columns'] = columns.value
			}

			// vm.refreshEditValueCol(vm.editFrame);
			refreshChildCol(selectChildren[0]);
			initGlobalTable(selectChildren[0]);

		}
	};

	function initGlobalTable(childObj : any, disChange ?: any, isCallBack ?: any) {

		//添加objNo
		for (let i = 0; i < childObj.tableData.length; i++) {
			childObj.tableData[i].objNo = (i + 1).toString();
			childObj.tableData[i].colInfo = childObj.columns;
			if (!childObj.tableData[i].guid) {
				childObj.tableData[i].guid = guid();
			}


			// if (!disChange) {
			// 	for (let j = 0; j < childObj.columns.length; j++) {
			// 		if (childObj.columns[j].colChange) {
			// 			handlerControlChange(i, childObj.columns[j].colChange);
			// 		}
			// 	}
			// }
			// if (isCallBack) {
			// 	for (let j = 0; j < childObj.columns.length; j++) {
			// 		if (childObj.columns[j].colCallBack) {
			// 			handlerControlChange(i, childObj.columns[j].colCallBack);
			// 		}
			// 	}
			// }
		}
	};

	function //生成GUID
		guid() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			let r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	}

	function handlerControlChange() {

	}



	function dealSelectDatasource(sql : any, formDesignObj : any) {

		requestByUrl({
			config: {
				baseURL: "/SQLData/GetDataBySql"
			},
			url: '',
			method: 'POST',
			data: {
				sql: sql
			},
			success(ret : any) {
				formDesignObj.controlProperty.select["sqlDataSource"] = ret.data.ds;
				formDesignObj.controlProperty.select["originDataSource"] = ret.data.ds;

				//判断隐藏值类型和当前赋值类型是否一致
				if (ret.data.ds.length > 0 && (formData[formDesignObj.baseProperty.controlName] !=
					undefined &&
					formData[formDesignObj.baseProperty.controlName] != null)) {
					let dataType = ref<any>("")
					dataType.value = typeof (ret.data.ds[0][formDesignObj.controlProperty.select
						.hiddenValue
					]);
					if (dataType.value != typeof (formData[formDesignObj.baseProperty.controlName])) {
						if (dataType.value == "int" || dataType.value == "number") {
							formData[formDesignObj.baseProperty.controlName] = parseInt(formData[formDesignObj.baseProperty.controlName]);
						} else if (dataType.value == "boolean") {
							formData[formDesignObj.baseProperty.controlName] = Boolean(parseInt(
								formData[formDesignObj.baseProperty.controlName]));
						}
					} else {
						formData[formDesignObj.baseProperty.controlName] = formData[formDesignObj.baseProperty.controlName];
					}
					formData[formDesignObj.baseProperty.controlName + '_show'] = ''

					let curDs = ret.data.ds.filter(function (item : any) {
						return item[formDesignObj.controlProperty.select.hiddenValue] == formData[formDesignObj.baseProperty.controlName]
					});
					if (curDs.length > 0) {
						formData[formDesignObj.baseProperty.controlName + '_show'] = curDs[0][formDesignObj.controlProperty.select.displayValue]
					}
				}

			}
		})
	};

	function dealSelectDatasourceByTree(sql : any, formDesignObj : any) {
		requestByUrl({
			config: {
				baseURL: "/SQLData/GetDataBySql"
			},
			url: '',
			method: 'POST',
			data: {
				sql: sql,
				sqlParam: formData
			},
			success(ret : any) {

				if (ret.status == 200) {
					//绑定固定值
					formDesignObj.controlProperty.select["sqlDataSource"] = ret.data.ds;
					formDesignObj.controlProperty.select["originDataSource"] = ret.data.ds;
					formDesignObj.controlProperty.select["actualName"] = "";
					let actualList = ret.data.ds.filter(function (item : any) {
						return item[formDesignObj.controlProperty.select.hiddenValue] == formData[formDesignObj.baseProperty.controlName]
					});
					formData[formDesignObj.baseProperty.controlName + '_show'] = '';
					if (actualList.length > 0) {
						let displayValue = actualList.map(function (item : any) {
							return item[formDesignObj.controlProperty.select.displayValue]
						}).join(',');
						formDesignObj.controlProperty.select["actualName"] = displayValue;
						formData[formDesignObj.baseProperty.controlName + '_show'] = displayValue;
					} else {
						formData[formDesignObj.baseProperty.controlName + '_show'] = '';
					}
				} else {



				}



			},
			fail(err : any) {

			}
		})
	};



	function formatterDate(dateTime : any, format : any = "yyyy-MM-dd") {
		if (dateTime) {
			//根据传入的格式化字符串，进行格式化
			return uni.$utils.dateFormat(dateTime, format);
		} else {
			return dateTime;
		}
	}

	let APPRoleColChildList = ref<any>([]);
	let tabCurrent = ref(0)
	async function clickTabItem(data : any) {
		tabCurrent.value = data.index;
		const { title, index } = data;
		const currentTab = TabList.value[index];
		if (!currentTab || title === '关联单据') return;

		try {
			// ① 获取字段权限数据
			const ret = await permissionStore.getAPPRoleColFunByRoleID({
				request,
				moduleName: currentTab.name,
				moduleType: 'formlist',
			});

			const list = ret?.data?.ds ?? [];
			if (ret?.status !== 200 || list.length === 0) return;

			// ② 提前建立 columns 的 Map 索引 (O(n))
			const colMap = new Map<string, any>();
			for (const c of columns.value) colMap.set(c.colName, c);

			// ③ 合并权限 (O(n))
			const newMap = new Map<string, any>();
			for (const item of list) {
				const col = colMap.get(item.ColName);
				if (col) {
					item.IsEditRole = col.isReadOnly ? false : item.IsEditRole ?? true;
					item.IsViewRole = col.isHidden ? false : item.IsViewRole ?? true;
				}
				newMap.set(item.ColName, item);
			}

			// ④ 一次性替换引用，触发最少响应更新
			APPRoleColChildList.value = newMap;
		} catch (err) {
			console.error('clickTabItem error:', err);
		}
	}




	async function childPageInit(childObjData : any) {
		return requestByUrl({
			config: {
				baseURL: "/AppFormList/GetDataByName"
			},
			url: '',
			method: 'POST',
			data: {
				objName: childObjData.name
			}
		}).then(async (ret : any) => {
			if (ret.status == 200) {
				let filterCondition = uni.$utils.isEmpty(ret.data.ds[0]["filterCondition"]) ? "" : ret.data.ds[0]["filterCondition"];

				await childTableConfig({
					childObj: childObjData,
					columns: JSON.parse(ret.data.ds[0]["columnsConfig"]),
					workList: JSON.parse(ret.data.ds[0]["worksConfig"]),
					crudList: JSON.parse(ret.data.ds[0]["crudConfig"]),
					params: {
						isFormList: ret.data.ds[0]["isFormList"],
						physicalTableName: ret.data.ds[0]["physicalTableName"],
						isPaging: ret.data.ds[0]["isPaging"],
						filterCondition: filterCondition,
						defaultOrder: ret.data.ds[0]["defaultOrder"],
						detailName: ret.data.ds[0]["detailName"],
						isFormEdit: false,
						rowClassCol: ret.data.ds[0]["rowClassCol"],
						onReadyCallBack: ret.data.ds[0]["onReadyCallBack"],
						colClassCol: ret.data.ds[0]["colClassCol"],

					}
				})
			}
		})
	};

	let columns = ref<any>([])
	let childObj = ref({});
	let tableData = ref([]);
	async function childTableConfig(options : any) {
		options.childObj["tableData"] = [];
		options.childObj["params"] = options.params;
		options.childObj["workList"] = options.workList;
		options.childObj["crudList"] = options.crudList;
		options.childObj["columns"] = options.columns;
		columns.value = JSON.parse(JSON.stringify(options.columns));

		childObj.value = uni.$utils.deepClone(options.childObj);

		let filterCondition = ref('1=1');
		if (options.params.filterCondition) {
			filterCondition.value += ' and ' + options.params.filterCondition;
		}
		let connectParams = formData[options.childObj['connectParams']];
		if (!connectParams) {
			filterCondition.value += " and 1=0 ";
		} else {
			filterCondition.value += " and " + options.childObj['connectParams'] + "='" + connectParams + "'";
		}
		let titleCols = options.childObj.columns.filter(function (item : any) {
			return item.isTitle == true
		});
		if (titleCols.length > 0) {
			options.childObj["titleCol"] = titleCols[0];
		};

		return requestByUrl({
			config: {
				baseURL: "/SQLData/GetDataByPhysicalTableNameByQueryPaging_Uniapp"
			},
			url: '',
			method: 'POST',
			data: {
				tableName: options.params.physicalTableName,
				columnsStr: JSON.stringify([]),
				currentCol: '',
				pageIndex: 1,
				pageSize: 9999,
				isForm: (options.params.isFormList || true).toString(),
				filterCondition: filterCondition.value,
				defaultOrder: options.params.defaultOrder || ''
			},
			fail(err : any) {
				tableData.value = [];
			}
		}).then(async (ret : any) => {
			// 
			if (origin.value != 'draft' || isUpdate.value) { // 非草稿箱
				options.childObj["tableData"] = ret.data.ds;
			}
			await refreshChildCol(options.childObj);
		})
	};

	async function refreshChildCol(childObjData : any) {

		for (let i = 0; i < childObjData.columns.length; i++) {

			//下拉框数据加载
			if (childObjData.columns[i].colType == 2 && childObjData.columns[i].selDetail.type < 3) {
				let sql = childObjData.columns[i].selDetail.dataSource;
				let selDetailObj = childObjData.columns[i].selDetail;
				await changeDataAjax(sql, "1=1", function (data : any, requestObj : any) {
					requestObj.sqlDataSource = data;
				}, selDetailObj);
			} else if (childObjData.columns[i].colType == 2 && childObjData.columns[i].selDetail.type == 3) {
				let valueList = [];

				for (let j = 0; j < childObjData.tableData.length; j++) {

					if (!uni.$utils.isEmpty(childObjData.tableData[j][childObjData.columns[i].colName])) {
						for (let k = 0; k < childObjData.tableData[j][childObjData.columns[i].colName].toString().split(',').length; k++) {
							valueList.push("'" + childObjData.tableData[j][childObjData.columns[i].colName].toString().split(',')[k] + "'");
						}
					}
				};

				if (valueList.length > 0) {
					let selDetailObj = childObjData.columns[i].selDetail;
					await changeDataAjax(childObjData.columns[i].selDetail.dataSource, childObjData.columns[i]
						.selDetail.hiddenValue + " in (" + valueList.join(',') + ") ",
						function (data : any, requestObj : any) {
							requestObj.sqlDataSource = data;
						}, selDetailObj);
				} else {
					childObjData.columns[i].selDetail.sqlDataSource = [];
				}
			}
		};
		// if (isUpdate.value) {
		transParamsDefault();
		// }
		initGlobalTable(childObjData);
	}
	let changeDataSource = ref<any>([]);
	async function changeDataAjax(datasource : any, query : any, callBack : any, requestObj : any) {
		let dsResult = changeDataSource.value.filter((item : any) =>
			item.datasource == datasource && item.query == query
		);
		if (dsResult.length == 0) {
			let returnData : any[] = [];
			let sql = "select * from (" + datasource + ")t where " + query;

			if (sql.indexOf('@') >= 0) {
				for (const name in formData) {
					const repalceValue = "'" + formData[name] + "'";
					sql = sql.replace(new RegExp("@" + name, "g"), repalceValue);
				}
			}

			return requestByUrl({
				config: { baseURL: "/SQLData/GetDataBySql" },
				url: '',
				method: 'POST',
				data: { sql },
				success(ret : any) {
					returnData = ret.data.ds;
					changeDataSource.value.push({
						datasource,
						query,
						data: returnData
					});

					callBack && callBack(returnData, requestObj);
				},
				fail(err : any) {

				}
			});
		} else {
			callBack(dsResult[0].data, requestObj);
		}
	}


	function filterImportConfigList() {

		return importConfig.value.filter(function (config : any) {
			// 
			return btn_showCondition(3, config)
		})
	}
	function importData(config : any) {
		// 
		if (config.js) {
			let script = config.js.replace(/vm\./g, '');
			script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');
			// 
			run(script, {
				// 注入UniApp环境的API（如uni对象）
				uni: uni,
				formData: formData,
				importEvent: importEvent,
				config: config,
				post,
				layer
			})


		} else {

			importEvent(config);
		}
	};
	function openImportSheet() {
		let mapData = filterImportConfigList().map((item : any) => {
			return {
				...item,
				title: item.btnName
			}
		});

		// #ifdef APP-HARMONY

		// #endif

		// #ifdef APP-PLUS
		plus.nativeUI.actionSheet({
			cancel: "取消",
			buttons: mapData
		}, function (event) {
			if (event.index > 0) {
				// importData(mapData[event.index - 1])
			}
		});
		// #endif
	};

	const importDataCurrent = computed(() => {
		let routes = getCurrentPages(); //当前页面栈
		// pda监听器
		return "importData" + routes.length;
	});
	function importEvent(config : any) {

		let obj = {
			formDesign: config.reportDesignConfig,
			sql: config.sql,
			importJs: config.importJs,
			columns: config.columns,
			originFormData: formData,
			name: config.btnName,
		};
		mainStore.ImportPickerSetting = obj;
		uni.navigateTo({
			url: '/commonPage/Tool/importPicker' + '?listen=' + importDataCurrent.value
		})

	}
	//按钮显示条件判断
	function btn_showCondition(type : any, btn : any) {

		try {

			let result = ref(true);
			let showScript = "";
			//普通crud
			if (type == 1) {
				if (btn == "新增") {
					showScript = crudList.value[0].show;
				} else if (btn == "编辑") {
					showScript = crudList.value[1].show;

				} else if (btn == "删除") {
					showScript = crudList.value[2].show;
				}
			}
			//业务按钮
			else if (type == 2) {
				showScript = btn.show;
			}
			//调入按钮
			else if (type == 3) {
				showScript = btn.btnShow;
			}
			if (showScript) {
				let script = showScript.replace(/vm\./g, '');
				script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');

				run(`${"result.value=(" + script + ")"}`, {
					// 注入UniApp环境的API（如uni对象）
					uni: uni,
					formData: formData,
					result,
					post,
					layer
				})
			}

			return result.value;
		} catch (e) {
			return false;
		}
	}

	async function btn_showCondition1(data : any) {
		try {
			if (data.length) {
				let filterData = await data.filter((btn : any) => {
					let script = btn.show.replace(/vm\./g, '');
					script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');
					if (uni.$utils.isEmpty(script)) {
						return true;
					} else {
						let flash = ref(false);
						const runInfo = `flash.value=${script}`;

						run(runInfo, {
							uni: uni,
							formData: formData,
							approvalConfig: approvalConfig,
							flash: flash,
							post,
							layer
						});
						return flash.value
					}
				});
				return filterData;
			}
			return [];
		} catch (error) {
			return [];
		}
	}


	/**
	 * 过滤数组数据
	 * @param {Array} 过滤数组
	 * @param {Function} 过滤条件
	 * @return {Array} 返回过滤后的数据
	 */
	const getFilterData = (data : any[], filter : (ret : any) => boolean) : any[] => {
		return data.filter(filter)
	}

	// 判断当前按钮是否允许显示
	function btnAllowShowFun(functionName : string) {
		// 检查是否存在任何项的 FunName 与传入的字符串相匹配
		const isFunctionDenied = permissionStore.filterUnPermissionConfig.some((item : any) => item.FunName === functionName);
		return !isFunctionDenied;
	}


	/**
	 * 发起审批
	 */
	function startApprove() {
		uni.$utils.layer.alert("暂未开放此功能！")


	};
	function formApprove() {

		uni.$utils.layer.alert("暂未开放此功能！")

	};
	function cancelApprove() {

		uni.$utils.layer.alert("暂未开放此功能！")

	};

	let requestChildList = ref<any>([]);
	// 保存事件
	function saveRow(callBackEvent ?: any, isCancelSubmit ?: any) {
		if (!enabledSubmitBtn.value && !isCancelSubmit) {
			return;
		} else {
			enabledSubmitBtn.value = false;
			// const testTaskAction = async (context: Context, data ?: unknown) => {
			// 	
			// 	
			// }
			// const testTaskOpt = {
			// 	action: testTaskAction,
			// 	addNow: true,
			// 	id: 'testTask',
			// 	chainName: '11', 
			// } as TaskOptions;
			// const testTask = new Task(testTaskOpt);

			const scriptStr = isUpdate.value ?
				crudList.value[1].script :
				crudList.value[0].script


			if (scriptStr?.includes('buttonCoreTask(')) {
				const script = scriptStr.replace(
					/let\s+buttonType\s*=\s*"[^"]*"/,
					'let buttonType = "Save"'
				).replace(
					"work.sql",
					'""'
				);
				if (script.includes("saveRowByTask")) {
					throw new Error('[saveRow]: 保存的script中不能调用自身');
				}
				console.log(script);

				selfWorkTaskHandler(
					script,
					'formData',
					{
						uni,
						formData,
						importEvent,
						crudList: crudList.value,
					}
				);
				return;
			}

			//带有Js脚本的，则先执行脚本
			if (scriptStr) {
				// eval(crudList.value[0].script);
				// new Function(crudList.value[0].script)();
				let script = scriptStr.replace(/vm\./g, '');
				script = script.replace(/(?<![A-Za-z])(\[\s*['"])/g, 'formData$1');
				run(`
				${script}
				`, {
					// 注入UniApp环境的API（如uni对象）
					uni: uni,
					formData: formData,
					importEvent: importEvent,
					crudList: crudList.value,
					post,
					layer
				})
			}
			//验证主表必填项
			let valitedResult = valitedRequired();

			if (valitedResult.status == 500) {
				uni.showToast({
					title: valitedResult.msg,
					icon: 'error'
				});
				enabledSubmitBtn.value = true;
				return;
			};
			// 判断子表是否存在，存在则验证子表
			// 判断是否存在子表数据

			if (childFormList.value.length && childFormList.value[0].tableData.length) {
				//同步外键值
				for (let i = 0; i < childFormList.value.length; i++) {
					let connectParams = childFormList.value[i].connectParams;
					for (let j = 0; j < childFormList.value[i].tableData.length; j++) {
						childFormList.value[i].tableData[j][connectParams] = formData[connectParams];
					}
					for (let j = 0; j < childFormList.value[i].crud.create.length; j++) {
						childFormList.value[i].crud.create[j][connectParams] = formData[connectParams];
					}
					for (let j = 0; j < childFormList.value[i].crud.update.length; j++) {
						childFormList.value[i].crud.update[j][connectParams] = formData[connectParams];
					}
					for (let j = 0; j < childFormList.value[i].crud.delete.length; j++) {
						childFormList.value[i].crud.delete[j][connectParams] = formData[connectParams];
					}
				};


				let isSuccess = true;
				requestChildList.value = [];
				let errorStr = '';

				for (let i = 0; i < childFormList.value.length; i++) {
					if (childFormList.value[i].crud.create.length > 0 ||
						childFormList.value[i].crud.update.length > 0 ||
						childFormList.value[i].crud.delete.length > 0) {
						//验证子表必填项


						let result = valitedChildForm(
							childFormList.value[i],
							childFormList.value[i].crud.create,
							childFormList.value[i].crud.update
						);


						if (!result.valited) {
							errorStr += result.valitedColumn + "不能为空!";
							isSuccess = false;
						};



					}
				}
				if (!isSuccess) {
					uni.showToast({
						title: errorStr,
						icon: 'error'
					});
					enabledSubmitBtn.value = true;
					return;
				}
			}




			Object.assign(formData, {
				P_UserID: UserInfo?.UserID || '',
				P_UserName: UserInfo?.UserName || '',
				P_UserCode: UserInfo?.UserCode || ''
			});
			setTimeout(function () {
				//新增操作
				if (!isUpdate.value) {
					saveRowByAdd(callBackEvent);

				} else {
					saveRowByEdit(callBackEvent);
				}
			}, 0)
		}
	};
	//主表验证必填
	function valitedRequired() {
		let resultObj = {
			status: 200,
			msg: ""
		};
		for (let i = 0; i < formDesign.value.length; i++) {
			if (formDesign.value[i].baseProperty.isRequired) {
				if (uni.$utils.isEmpty(formData[formDesign.value[i].baseProperty.controlName])) {
					resultObj = {
						status: 500,
						msg: formDesign.value[i].baseProperty.labelName + "字段不能为空!"
					};
				}
			}
		}
		return resultObj;
	};
	//验证子表必填项
	function valitedChildForm(childForm ?: any, createObjs ?: any, updateObjs ?: any) {
		let valited = true;
		let valitedColumn = "";
		let index = 0;

		for (let i = 0; i < childForm.columns.length; i++) {
			if (childForm.columns[i].isRequired) {


				for (let j = 0; j < createObjs.length; j++) {
					if (createObjs[j][childForm.columns[i].colName] === undefined ||
						createObjs[j][childForm.columns[i].colName] === null ||
						createObjs[j][childForm.columns[i].colName] === ""
					) {
						index = j;
						valited = false;
						valitedColumn = childForm.columns[i].colDesc;
					}
				}
				for (let j = 0; j < updateObjs.length; j++) {
					if (updateObjs[j][childForm.columns[i].colName] === undefined ||
						updateObjs[j][childForm.columns[i].colName] === null ||
						updateObjs[j][childForm.columns[i].colName] === ""
					) {
						index = j;
						valited = false;
						valitedColumn = childForm.columns[i].colDesc;
					}
				}
			}
		};

		return {
			valited: valited,
			valitedColumn: valitedColumn,
			index: index
		};
	};
	// 新增
	function saveRowByAdd(callBackEvent ?: any) {
		let postData = reactive({
			tableName: physicalTableName.value,
			createWorkSQL: crudList.value[0].sql
		});
		Object.assign(postData, formData);




		requestByUrl({
			config: { baseURL: "/SQLData/InsertSingleRow" },
			url: '',
			method: 'POST',
			data: postData,
			success(ret : any) {

				isUpdate.value = true;
				let keyObj = ret.data;
				keyName.value = keyObj.keyName;
				keyValue.value = keyObj.keyValue;
				formData[keyName.value] = keyValue.value;
				if (ret.data.dataTable.length > 0) {
					Object.assign(formData, ret.data.dataTable[0]);
				};


				// 判断是否存在子表
				if (childFormList.value.length && childFormList.value[0].tableData.length) {

					//同步外键值
					for (let i = 0; i < childFormList.value.length; i++) {
						let connectParams = childFormList.value[i].connectParams;
						for (let j = 0; j < childFormList.value[i].tableData.length; j++) {
							childFormList.value[i].tableData[j][connectParams] = formData[connectParams];
						}
						for (let j = 0; j < childFormList.value[i].crud.create.length; j++) {
							childFormList.value[i].crud.create[j][connectParams] = formData[connectParams];
						}
						for (let j = 0; j < childFormList.value[i].crud.update.length; j++) {
							childFormList.value[i].crud.update[j][connectParams] = formData[connectParams];
						}
						for (let j = 0; j < childFormList.value[i].crud.delete.length; j++) {
							childFormList.value[i].crud.delete[j][connectParams] = formData[connectParams];
						}


						// let createObj = JSON.parse(JSON.stringify(childFormList.value[i].crud.create));
						// createObj.colInfo = [];
						// let updateObj = JSON.parse(JSON.stringify(childFormList.value[i].crud.update));
						// updateObj.colInfo = [];
						// let deleteObj = JSON.parse(JSON.stringify(childFormList.value[i].crud.delete));
						// deleteObj.colInfo = [];

						const createObj = childFormList.value[i].crud.create.map(({ colInfo, ...rest }) => rest);
						const updateObj = childFormList.value[i].crud.update.map(({ colInfo, ...rest }) => rest);
						const deleteObj = childFormList.value[i].crud.delete.map(({ colInfo, ...rest }) => rest);
						let PromiseParams = {
							tableName: childFormList.value[i].params.physicalTableName,
							createStr: JSON.stringify(createObj),
							updateStr: JSON.stringify(updateObj),
							deleteStr: JSON.stringify(deleteObj),
							createWork: childFormList.value[i].crudList[0].sql,
							updateWork: childFormList.value[i].crudList[1].sql,
							deleteWork: childFormList.value[i].crudList[2].sql
						}




						let requestSql = PromiseRequestByUrl({
							config: {
								baseURL: "/FormList/SaveData_uniapp"
							},
							url: '',
							method: 'POST',
							data: PromiseParams
						});

						requestChildList.value.push(requestSql);

					};


					let isAllSuccess = 0;
					let isSuccess = true;
					//提交子表ajax
					let submitChildRequest = function (iNum ?: any, fininshCallBack ?: any) {
						if (requestChildList.value.length == 0) {
							fininshCallBack();
						}
						// 
						if (requestChildList.value[iNum]) {

							requestChildList.value[iNum].then(
								function (data : any) {

									isAllSuccess++;
									childPageInit(childFormList.value[iNum]);
									childFormList.value[iNum].crud.create = [];
									childFormList.value[iNum].crud.update = [];
									childFormList.value[iNum].crud.delete = [];
									iNum = iNum + 1;
									if (iNum < requestChildList.value.length) {
										submitChildRequest(iNum, fininshCallBack);
									} else {
										fininshCallBack();
									}
								},
								function (data : any) {

									isSuccess = false;
									// enabledSubmitBtn.value = true;
									isAllSuccess++;
									iNum = iNum + 1;
									if (iNum < requestChildList.value.length) {
										submitChildRequest(iNum + 1, fininshCallBack);
									} else {
										fininshCallBack();
									}
								});
						}
					}


					submitChildRequest(0, function () {
						if (isSuccess) {
							uni.showToast({
								title: "保存成功",
								icon: 'success'
							});
							refreshPage();
							//刷新整体表单
							//vm.initConfig(vm.detailName);
						} else {
							enabledSubmitBtn.value = true;
						}
						if (typeof (callBackEvent) == 'function') {
							callBackEvent();
						}
						if (crudList.value[1].finishSql) {
							Object.assign({
								sql: crudList.value[1].finishSql
							}, formData)

							requestByUrl({
								config: { baseURL: "/SQLData/QuerySql" },
								url: '',
								method: 'POST',
								data: formData,
								success(rest) {


								}
							})


						}


					})


				} else {
					// 不存在子表数据，直接提示成功
					uni.showToast({
						title: "保存成功",
						icon: 'success'
					});

					refreshPage();
				}

			}
		})


	}
	function saveRowByEdit(callBackEvent ?: any) {

		//任何保存前先调用主表验证SQL
		let checkSQL = crudList.value[1].sql;
		let isCheck = true;
		if (checkSQL) {

			let postData = reactive<any>({
				tableName: physicalTableName.value,
				keyValue: keyValue.value,
				updateWorkSQL: checkSQL
			});
			Object.assign(postData, formData);
			Object.keys(postData).forEach(item => {
				if (postData[item] == null || postData[item] == 'null') {
					delete postData[item]
				}
			});

			requestByUrl({
				config: { baseURL: "/SQLData/UpdateSingleRowByRollBack" },
				url: '',
				method: 'POST',
				data: postData,
				success(ret : any) {

					requestByUrl({
						config: { baseURL: "/SQLData/UpdateSingleRow" },
						url: '',
						method: 'POST',
						data: postData,
						success(res : any) {


							//同步外键值
							for (let i = 0; i < childFormList.value.length; i++) {
								let connectParams = childFormList.value[i].connectParams;
								for (let j = 0; j < childFormList.value[i].tableData.length; j++) {
									childFormList.value[i].tableData[j][connectParams] = formData[connectParams];
								}
								for (let j = 0; j < childFormList.value[i].crud.create.length; j++) {
									childFormList.value[i].crud.create[j][connectParams] = formData[connectParams];
								}
								for (let j = 0; j < childFormList.value[i].crud.update.length; j++) {
									childFormList.value[i].crud.update[j][connectParams] = formData[connectParams];
								}
								for (let j = 0; j < childFormList.value[i].crud.delete.length; j++) {
									childFormList.value[i].crud.delete[j][connectParams] = formData[connectParams];
								}


								// let createObj = JSON.parse(JSON.stringify(childFormList.value[i].crud.create));
								// createObj.colInfo = [];
								// let updateObj = JSON.parse(JSON.stringify(childFormList.value[i].crud.update));
								// updateObj.colInfo = [];
								// let deleteObj = JSON.parse(JSON.stringify(childFormList.value[i].crud.delete));
								// deleteObj.colInfo = [];

								const createObj = childFormList.value[i].crud.create.map(({ colInfo, ...rest }) => rest);
								const updateObj = childFormList.value[i].crud.update.map(({ colInfo, ...rest }) => rest);
								const deleteObj = childFormList.value[i].crud.delete.map(({ colInfo, ...rest }) => rest);
								let PromiseParams = {
									tableName: childFormList.value[i].params.physicalTableName,
									createStr: JSON.stringify(createObj),
									updateStr: JSON.stringify(updateObj),
									deleteStr: JSON.stringify(deleteObj),
									createWork: childFormList.value[i].crudList[0].sql,
									updateWork: childFormList.value[i].crudList[1].sql,
									deleteWork: childFormList.value[i].crudList[2].sql
								}

								let requestSql = PromiseRequestByUrl({
									config: {
										baseURL: "/FormList/SaveData_uniapp"
									},
									url: '',
									method: 'POST',
									data: PromiseParams
								});

								requestChildList.value.push(requestSql);

								requestSql.then(ret => {

								})
							};


							let isAllSuccess = 0;
							let isSuccess = true;
							//提交子表ajax
							let submitChildRequest = function (iNum ?: any, fininshCallBack ?: any) {
								if (requestChildList.value.length == 0) {
									fininshCallBack();
								}
								// 
								if (requestChildList.value[iNum]) {

									requestChildList.value[iNum].then(
										function (data : any) {

											isAllSuccess++;
											childPageInit(childFormList.value[iNum]);
											childFormList.value[iNum].crud.create = [];
											childFormList.value[iNum].crud.update = [];
											childFormList.value[iNum].crud.delete = [];
											iNum = iNum + 1;
											if (iNum < requestChildList.value.length) {
												submitChildRequest(iNum, fininshCallBack);
											} else {
												fininshCallBack();
											}
										},
										function (data : any) {

											isSuccess = false;
											// enabledSubmitBtn.value = true;
											isAllSuccess++;
											iNum = iNum + 1;
											if (iNum < requestChildList.value.length) {
												submitChildRequest(iNum + 1, fininshCallBack);
											} else {
												fininshCallBack();
											}
										});
								}
							}


							submitChildRequest(0, function () {
								if (isSuccess) {
									uni.showToast({
										title: "保存成功",
										icon: 'success'
									});
									refreshPage();
									//刷新整体表单
									//vm.initConfig(vm.detailName);
								} else {
									enabledSubmitBtn.value = true;
								}
								if (typeof (callBackEvent) == 'function') {
									callBackEvent();
								}
								if (crudList.value[1].finishSql) {
									Object.assign({
										sql: crudList.value[1].finishSql
									}, formData)

									requestByUrl({
										config: { baseURL: "/SQLData/QuerySql" },
										url: '',
										method: 'POST',
										data: formData,
										success(rest) {


										}
									})


								}


							})



						},
						fail(err : any) {

						}
					});


				},
				fail(err : any) {

				}
			});

		}

	};

	// 刷新当前页、列表、详情
	async function refreshPage() {
		// 刷新详情页面、审批待办
		uni.$emit('refreshToIndex'); // 刷新详情
		uni.$emit('refreshToApprove'); // 刷新审批待办


		// 详情页面刷新，会触发列表页面刷新
		let hasListPage = uni.$utils.findPageInStack("/commonPage/Form/index");

		// 判断是否存在详情页面栈
		if (!hasListPage.exists) {
			// 当不存在详情页面时，手动触发列表刷新
			uni.$emit('FormInitToRefresh', { // 触发列表刷新
				keyID: formData[keyName.value]
			});
		}
		//刷新整体表单
		await initConfig(detailName.value);
		if (!isUpdate.value) {
			uni.$emit('refreshDraftInfo'); // 触发草稿刷新
		}

	}

	// 默认返回页数
	let backNum = ref(1);
	function goBack(str : any = 'back') {
		backNum.value = 1;
		if (str == 'close') {
			let routes = getCurrentPages();
			let routePageCurrent = mainStore.appConfigInfo.routePageCurrent;
			backNum.value = routes.length - routePageCurrent;
		}

		uni.navigateBack({
			delta: backNum.value
		})
	}

	function post(sql : string, param ?: any, callBack ?: any, errorCallBack ?: any) {
		param["sql"] = sql;


		if (!uni.$utils.isEmpty(UserInfo)) {

			if (!param.hasOwnProperty("P_UserID")) {
				param.P_UserID = UserInfo.UserID;
			}
			if (!param.hasOwnProperty("P_UserName")) {
				param.P_UserName = UserInfo.UserName;
			}
			if (!param.hasOwnProperty("P_UserCode")) {
				param.P_UserCode = UserInfo.UserCode;
			}
		};
		requestByUrl({
			config: { baseURL: "/SQLData/QuerySql" },
			url: '',
			method: 'POST',
			data: param,
			success(ret : any) {
				callBack && callBack(ret);
			},
			fail(err : any) {
				errorCallBack && errorCallBack(err)
				// layer.alert(JSON.stringify(err), function () {

				// 	showMLoading.value = false;
				// 	enabledSubmitBtn.value = true;
				// })

			}
		});
	};


	onAllComplete(() => {

		showMLoading.value = false;
		enabledSubmitBtn.value = true;
	});

	onError((ret : any) => {
		console.log(ret);
		if (ret?.detail?.status == 500) {
			let msg = ret.detail.msg || "接口请求异常，请点击刷新或退出";
			layer.confirm(msg, {
				title: "提示",
				confirmText: "刷新",
				cancelText: "退出",
			}, function (ret) {
				if (ret.action == 'confirm') {
					initConfig(detailName.value);
				} else if (ret.action == 'cancel') {
					goBack();
				}

			});
		} else {
			layer.confirm(JSON.stringify(ret), {
				title: "请求失败，点击刷新或退出",
				confirmText: "刷新",
				cancelText: "退出",
			}, function (ret) {
				if (ret.action == 'confirm') {
					initConfig(detailName.value);
				} else if (ret.action == 'cancel') {
					goBack();
				}

			});
		}
	})


	let origin = ref("");
	let idByDraftList = ref(null)
	onLoad((option : any) => {
		// 判断是否存在传入值，origin 定义为 来源
		if (!uni.$utils.isEmpty(option)) {
			// 判断来源
			if (option.origin == 'draft') { // 草稿箱
				origin.value = 'draft';

				idByDraftList.value = id; // 赋值草稿主键ID
			} else if (option.origin == 'approveWaitList') { // 审批待办
				origin.value = 'approveWaitList';
			}
		}

		// 正在渲染页面数据
		initConfig(detailName.value);
	});

	onReady(() => {

		//弹窗下拉数据选择监听器
		uni.$on(selectPicker_formEditCurrent.value, function (data) {


			// 判定当前页面已进行修改
			isFormModified.value = true;
			let ret = data.data;
			//主表表单选择
			if (windowSelectType.value == 1) {
				if (ret) {
					formData[curSelectWindowObj.value.baseProperty.controlName] = ret[curSelectWindowObj.value.controlProperty.select.hiddenValue];
					//formData[curSelectWindowObj.baseProperty.controlName + '_show'] = ret[curSelectWindowObj.controlProperty.select.displayValue];
					formData[curSelectWindowObj.value.baseProperty.controlName + '_show'] = ret[curSelectWindowObj.value.controlProperty.select.displayValue];
					// 
					// 
					dataChange(curSelectWindowObj.value, ret);

					curSelectWindowObj.value = {};
				} else {
					formData[curSelectWindowObj.value.baseProperty.controlName] = '';
					formData[curSelectWindowObj.value.baseProperty.controlName + '_show'] = '';

					dataChange(curSelectWindowObj.value, ret);
					curSelectWindowObj.value = {};
				}
			} else if (windowSelectType.value == 2) {
				if (ret) {
					// 
					editValues[curSelectWindowObj2.value.colName] = ret[curSelectWindowObj2.value.selDetail.hiddenValue];
					editValues[curSelectWindowObj2.value.colName + '_show'] = ret[curSelectWindowObj2.value.selDetail.displayValue];
					// 
					itemDataChange(curSelectWindowObj2.value, editValues, editFrame, ret);
					curSelectWindowObj2.value = '';
				} else {
					editValues[curSelectWindowObj2.value.colName] = '';
					editValues[curSelectWindowObj2.value.colName + '_show'] = "";
					itemDataChange(curSelectWindowObj2.value, editValues, editFrame, ret);
					curSelectWindowObj2.value = '';
				}
				refreshEditValueCol(editFrame);
			}
		})

		// 导入数据监听
		uni.$on(importDataCurrent.value, (importValue : any) => {


			// 判定当前页面已进行修改
			isFormModified.value = true;

			let _columns = importValue.columns;
			let selections = importValue.selections;

			let colToColumnList = _columns.filter(function (item : any) {
				return item.colToColumn != undefined && item.colToColumn !== ""
			});
			let isMain = false;
			let mainCount = 0;
			let childFormDatas : any = [];

			for (let z = 0; z < childFormList.value.length; z++) {
				childFormDatas.push({
					name: childFormList.value[z].title,
					frameName: childFormList.value[z].name,
					record: []
				});
			};
			for (let i = 0; i < selections.length; i++) {
				for (let j = 0; j < colToColumnList.length; j++) {
					let toColumnNames = colToColumnList[j].colToColumn.split(',');
					for (let k = 0; k < toColumnNames.length; k++) {
						let nameKey = toColumnNames[k].split('.')[0];
						let nameValue = toColumnNames[k].split('.')[1];
						//主记录数据
						if (nameKey == "main" && !isMain) {
							mainCount++;
							if (formData[nameValue] != undefined) {
								formData[nameValue] = selections[i][colToColumnList[j].colName];
								//vm.execChangeEvent(colToColumnList[j].colName, 1);
								//vm.execChangeEvent(colToColumnList[j].colName, 2);
							}
						}
						if (nameKey != "main") {
							let recordList = childFormDatas.filter(function (item : any) {
								return item.name == nameKey || item.frameName == nameKey
							});
							if (recordList.length > 0) {


								for (let r = 0; r < recordList.length; r++) {
									if (recordList[r].record[i] == undefined) {
										recordList[r].record[i] = {};
									}
									recordList[r].record[i][nameValue] = selections[i][colToColumnList[j].colName
									];
								}
							}
						}
					}
				}
				if (mainCount > 0) {
					isMain = true;
				}
			}


			//插入子表数据
			for (let i = 0; i < childFormDatas.length; i++) {
				if (childFormDatas[i].record.length > 0) {
					if (JSON.stringify(childFormDatas[i].record) != "{}") {
						//插入子表
						insertImportData(childFormDatas[i].frameName, childFormDatas[i].record);
					}
				}
			}
		})
	})

	onMounted(() => {

		nextTick(() => {
			setTimeout(() => {

				uni.createSelectorQuery().select('.btn-height').boundingClientRect(rect => {
					// that.btnStyle = rect

					Object.assign(btnStyle, rect);

				}).exec();
			}, 300)
		});

	})

	let btnStyle = reactive<any>({})

	const buttonClasses = computed(() => {
		return {
			'small-font': btnStyle.width < 80,
			'disabled': !enabledSubmitBtn.value
		}
	});
	const buttonStyles = computed(() => {
		return {
			height: btnStyle.height ? `${btnStyle.height}px` : 'auto',
			'line-height': '20px'
		}
	});


	onUnload(() => {

		uni.$off(selectPicker_formEditCurrent.value);
		uni.$off(importDataCurrent.value);
		uni.$off("switch-to-next-item");
	});

	let isShowingConfirm = ref(false);
	function showBackConfirm() {
		if (isShowingConfirm.value) return;
		let backType = true;
		isShowingConfirm.value = true;
		layer.confirm('当前页面已修改，是否确认退出？', function (ret) {
			if (ret.action == "confirm") {
				backType = false;
				isShowingConfirm.value = false;
				isFormModified.value = false;
				uni.navigateBack({
					delta: backNum.value
				});
			} else {
				isShowingConfirm.value = false;
			}
		})
		return backType;
	}

	onBackPress((options) => {
		if (isFormModified.value) {
			return showBackConfirm() // 显示确认弹窗
			// return true // 拦截返回操作（关键步骤）
		}
		// 未修改则正常返回
		return false
	})

	const scriptUsedAPI = {
		Task,
		enabledSubmitBtn,
		TimeUnits,
		TaskType,
		TaskTriggerMode,
		saveRowByTask,
		buttonCoreTask,
		pageRefreshTask,
		pageRedirect,
		postSqlByTask,
		post,
		inventoryStore,
		mainStore,
		userStore,
		permissionStore,
		layer: uni.$utils.layer,
	};
	async function selfWorkTaskHandler(
		script : string,
		dataName : string,
		injectedAPI : { [key : string] : any }
	) : Promise<string> {
		try {


			script = script.replace(/vm\./g, '');
			script = script.replace(/(?<![A-Za-z'"])(\[\s*['"])/g, `${dataName}$1`);
			Object.assign(injectedAPI, scriptUsedAPI);
			injectedAPI.injectedAPI = injectedAPI;





			return await run(script, injectedAPI) ?? ""; // 注入UniApp环境的API（如uni对象）
		} catch (error : unknown) {
			enabledSubmitBtn.value = true;
			uni.$utils.hideLoading();
			if (error.message) {
				let message = error.message;
				// debugger;
				if (
					message.startsWith("the id of task:") &&
					message.endsWith(" is already exist!")
				) {
					message = '重复操作';
				}
				layer.alert(message, {
					icon: 2,
					title: '错误信息',
					btn: ['确定']
				});
			}
			console.error('An error occurred:', error);
			return "";
		}
	}

	async function saveRowByTask(
		chainName : string,
		beforeTask : string[],
		timeSuffix : string,
	) : Promise<string> {
		const beforeTaskStr =
			beforeTask.map(id => `'${id}'`).join(', ');
		let script = isUpdate.value ?
			crudList.value[1].script :
			crudList.value[0].script
		if (!(script?.trim())) {
			throw new Error('新增或者编辑按钮没有配置');
		}
		script = script.replace(
			'//configReplace',
			`
				taskChainName = "${chainName}";
				timeSuffix = '${timeSuffix}';
				beforeTask = [...[], ${beforeTaskStr}];
				injection.afterInnerCode = () => {
					setEndConfig = false;
				}
				//configReplace
			`
		).replace(
			/let\s+buttonType\s*=\s*"[^"]*"/,
			'let buttonType = "Save"'
		).replace(
			"work.sql",
			'""'
		);
		if (script.includes("saveRowByTask")) {
			throw new Error('[saveRowByTask]: 保存的script中不能调用自身');
		}
		return await selfWorkTaskHandler(
			script,
			'formData',
			{
				uni,
				formData,
				importEvent,
				crudList: crudList.value,
			}
		);
	}

	function buttonCoreTask(
		buttonType : string,
		sql : string,
		params : { [key : string] : any },
		beforeTask : string[],
		timeSuffix : string,
	) : string {
		switch (buttonType) {
			case "Save":
				return saveRowCoreByTask(params, beforeTask, timeSuffix);
			case "Self":
			default:
				return postSqlByTask(sql, params, beforeTask, timeSuffix);
		}
	}

	function postSqlByTask(
		sql : string,
		params : { [key : string] : any },
		beforeTask : string[],
		timeSuffix : string,
	) : string {
		const chainName = Task.getTask(beforeTask[0])?.chainName;
		if (!chainName) {
			throw new Error("[postSqlByTask]: can't get chainName By beforeTask")
		}
		const action = async (context : Context, data ?: unknown) => {


			params = await
				getCurrentParams(params, context.data?.injectedAPI);
			params["sql"] = sql;
			if (!uni.$utils.isEmpty(UserInfo)) {

				if (!params.hasOwnProperty("P_UserID")) {
					params.P_UserID = UserInfo.UserID;
				}
				if (!params.hasOwnProperty("P_UserName")) {
					params.P_UserName = UserInfo.UserName;
				}
				if (!params.hasOwnProperty("P_UserCode")) {
					params.P_UserCode = UserInfo.UserCode;
				}
			};


			return requestByUrl({
				config: { baseURL: "/SQLData/QuerySql" },
				url: '',
				method: 'POST',
				data: params,
			}).then((data) => {
				if (data?.status === 200) {
					return data.data;
				} else if (data?.status === 500) {

					layer.alert(data.msg, {
						icon: 2,
						title: '错误信息',
						btn: ['确定']
					});
					throw new Error(data.msg);
				} else {
					throw new Error(String(data));
				}
			});
		}
		const opt = {
			action,
			addNow: true,
			id: chainName + '-postSqlByTask' + timeSuffix,
			type: TaskType.REQUEST,
			chainName,
			beforeTask,
			triggerMode: TaskTriggerMode.Or,
		} as TaskOptions;
		const task = new Task(opt);
		return task.id;
	}

	function saveRowCoreByTask(
		params : { [key : string] : any },
		beforeTask : string[],
		timeSuffix : string,
	) : string {
		const chainName = Task.getTask(beforeTask[0])?.chainName;
		if (!chainName) {


			throw new Error("[saveRowCoreByTask]: can't get chainName By beforeTask")
		}

		const savePreTaskAction =
			async (context : Context, data ?: unknown) => {
				//验证主表必填项
				let valitedResult = valitedRequired();

				if (valitedResult.status == 500) {
					layer.alert(valitedResult.msg, {
						icon: 2,
						title: '错误信息',
						btn: ['确定']
					});
					enabledSubmitBtn.value = true;
					return false;
				};
				// 判断子表是否存在，存在则验证子表
				// 判断是否存在子表数据

				if (childFormList.value.length && childFormList.value[0].tableData.length) {
					//同步外键值
					for (let i = 0; i < childFormList.value.length; i++) {
						let connectParams = childFormList.value[i].connectParams;
						for (let j = 0; j < childFormList.value[i].tableData.length; j++) {
							childFormList.value[i].tableData[j][connectParams] = formData[connectParams];
						}
						for (let j = 0; j < childFormList.value[i].crud.create.length; j++) {
							childFormList.value[i].crud.create[j][connectParams] = formData[connectParams];
						}
						for (let j = 0; j < childFormList.value[i].crud.update.length; j++) {
							childFormList.value[i].crud.update[j][connectParams] = formData[connectParams];
						}
						for (let j = 0; j < childFormList.value[i].crud.delete.length; j++) {
							childFormList.value[i].crud.delete[j][connectParams] = formData[connectParams];
						}
					};


					let isSuccess = true;
					requestChildList.value = [];
					let errorStr = '';

					for (let i = 0; i < childFormList.value.length; i++) {
						if (childFormList.value[i].crud.create.length > 0 ||
							childFormList.value[i].crud.update.length > 0 ||
							childFormList.value[i].crud.delete.length > 0) {
							//验证子表必填项
							let result = valitedChildForm(
								childFormList.value[i],
								childFormList.value[i].crud.create,
								childFormList.value[i].crud.update
							);
							if (!result.valited) {
								errorStr += result.valitedColumn + "不能为空!";
								isSuccess = false;
							};
						}
					}
					if (!isSuccess) {
						layer.alert(errorStr, {
							icon: 2,
							title: '错误信息',
							btn: ['确定']
						});
						enabledSubmitBtn.value = true;
						return false;
					}
				}

				Object.assign(formData, {
					P_UserID: UserInfo?.UserID || '',
					P_UserName: UserInfo?.UserName || '',
					P_UserCode: UserInfo?.UserCode || ''
				});
				return true;
			}
		const savePreTaskOpt = {
			action: savePreTaskAction,
			addNow: true,
			id: 'savePreTask' + timeSuffix,
			chainName,
			beforeTask,
			triggerMode: TaskTriggerMode.Or,
		} as TaskOptions;
		const savePreTask = new Task(savePreTaskOpt);

		const saveJudgeAddTaskAction =
			async (context : Context, data ?: unknown) => {
				return !isUpdate.value;
			}
		const saveJudgeAddTaskOpt = {
			action: saveJudgeAddTaskAction,
			addNow: true,
			id: 'saveJudgeAddTask' + timeSuffix,
			chainName,
			beforeTask: [savePreTask.id],
			triggerMode: TaskTriggerMode.Or,
		} as TaskOptions;
		const saveJudgeAddTask = new Task(saveJudgeAddTaskOpt);

		const saveJudgeEditTaskAction =
			async (context : Context, data ?: unknown) => {
				return isUpdate.value;
			}
		const saveJudgeEditTaskOpt = {
			action: saveJudgeEditTaskAction,
			addNow: true,
			id: 'saveJudgeEditTask' + timeSuffix,
			chainName,
			beforeTask: [savePreTask.id],
			triggerMode: TaskTriggerMode.Or,
		} as TaskOptions;
		const saveJudgeEditTask = new Task(saveJudgeEditTaskOpt);


		const addRowTaskAction =
			async (context : Context, data ?: unknown) => {
				let postData = reactive({
					tableName: physicalTableName.value,
					createWorkSQL: crudList.value[0].sql || '[this]'
				});
				const currentParams = await
					getCurrentParams(params, context.data?.injectedAPI);
				Object.assign(postData, formData, currentParams);




				return requestByUrl({
					config: { baseURL: "/SQLData/InsertSingleRow" },
					url: '',
					method: 'POST',
					data: postData,
				}).then((data : any) => {

					if (data?.status === 200) {
						isUpdate.value = true;
						let keyObj = data.data;
						keyName.value = keyObj.keyName;
						keyValue.value = keyObj.keyValue;
						formData[keyName.value] = keyValue.value;
						if (data.data.dataTable.length > 0) {
							Object.assign(formData, data.data.dataTable[0]);
						};
						return data.data;
					} else if (data?.status === 500) {

						layer.alert(data.msg, {
							icon: 2,
							title: '错误信息',
							btn: ['确定']
						});
						throw new Error(data.msg);
					} else {
						throw new Error(String(data));
					}
				});
			};
		const addRowTaskOpt = {
			action: addRowTaskAction,
			addNow: true,
			id: 'addRowTask' + timeSuffix,
			type: TaskType.REQUEST,
			chainName,
			beforeTask: [saveJudgeAddTask.id],
			triggerMode: TaskTriggerMode.Or,
		} as TaskOptions;
		const addRowTask = new Task(addRowTaskOpt);

		const editRowTaskAction =
			async (context : Context, data ?: unknown) => {
				let postData = reactive<any>({
					tableName: physicalTableName.value,
					keyValue: keyValue.value,
					updateWorkSQL: crudList.value[1].sql || '[this]'
				});
				Object.assign(postData, formData);
				Object.keys(postData).forEach(item => {
					if (postData[item] == null || postData[item] == 'null') {
						delete postData[item]
					}
				});
				const currentParams = await
					getCurrentParams(params, context.data?.injectedAPI);
				Object.assign(postData, currentParams);
				return requestByUrl({
					config: { baseURL: "/SQLData/UpdateSingleRow" },
					url: '',
					method: 'POST',
					data: postData,
				}).then((data : any) => {
					if (data?.status === 200) {
						return data.data;
					} else if (data?.status === 500) {

						layer.alert(data.msg, {
							icon: 2,
							title: '错误信息',
							btn: ['确定']
						});
						throw new Error(data.msg);
					} else {
						throw new Error(String(data));
					}
				});
			};
		const editRowTaskOpt = {
			action: editRowTaskAction,
			addNow: true,
			id: 'editRowTask' + timeSuffix,
			type: TaskType.REQUEST,
			chainName,
			beforeTask: [saveJudgeEditTask.id],
			triggerMode: TaskTriggerMode.Or,
		} as TaskOptions;
		const editRowTask = new Task(editRowTaskOpt);

		const childTaskList = [];
		const childTaskActionList = [];
		const childTaskOptList = [];
		const submitTaskList = [];
		const submitTaskActionList = [];
		const submitTaskOptList = [];
		for (let i = 0; i < childFormList.value.length; i++) {
			childTaskActionList[i] =
				async (context : Context, taskData : { listIndex : number }) => {
					const index = taskData.listIndex;
					let connectParams = childFormList.value[index].connectParams;
					for (let j = 0; j < childFormList.value[index].tableData.length; j++) {
						childFormList.value[index].tableData[j][connectParams] = formData[connectParams];
					}
					for (let j = 0; j < childFormList.value[index].crud.create.length; j++) {
						childFormList.value[index].crud.create[j][connectParams] = formData[connectParams];
					}
					for (let j = 0; j < childFormList.value[index].crud.update.length; j++) {
						childFormList.value[index].crud.update[j][connectParams] = formData[connectParams];
					}
					for (let j = 0; j < childFormList.value[index].crud.delete.length; j++) {
						childFormList.value[index].crud.delete[j][connectParams] = formData[connectParams];
					}

					// let createObj = JSON.parse(JSON.stringify(childFormList.value[index].crud.create));
					// createObj.colInfo = [];
					// let updateObj = JSON.parse(JSON.stringify(childFormList.value[index].crud.update));
					// updateObj.colInfo = [];
					// let deleteObj = JSON.parse(JSON.stringify(childFormList.value[index].crud.delete));
					// deleteObj.colInfo = [];

					const createObj = childFormList.value[index].crud.create.map(({ colInfo, ...rest }) => rest);
					const updateObj = childFormList.value[index].crud.update.map(({ colInfo, ...rest }) => rest);
					const deleteObj = childFormList.value[index].crud.delete.map(({ colInfo, ...rest }) => rest);

					let PromiseParams = {
						tableName: childFormList.value[index].params.physicalTableName,
						createStr: JSON.stringify(createObj),
						updateStr: JSON.stringify(updateObj),
						deleteStr: JSON.stringify(deleteObj),
						createWork: childFormList.value[index].crudList[0].sql,
						updateWork: childFormList.value[index].crudList[1].sql,
						deleteWork: childFormList.value[index].crudList[2].sql
					}
					// 
					// 


					return PromiseRequestByUrl({
						config: {
							baseURL: "/FormList/SaveData_uniapp"
						},
						url: '',
						method: 'POST',
						data: PromiseParams
					}).then((data : any) => {
						if (data?.status === 200) {
							return data.data;
						} else if (data?.status === 500) {

							layer.alert(data.msg, {
								icon: 2,
								title: '错误信息',
								btn: ['确定']
							});
							throw new Error(data.msg);
						} else {
							throw new Error(String(data));
						}
					});
				};
			childTaskOptList[i] = {
				action: childTaskActionList[i],
				addNow: true,
				id: `childTask-${i}${timeSuffix}`,
				type: i == 0 ? TaskType.REQUEST : TaskType.NORMAL,
				chainName,
				data: { listIndex: i },
				beforeTask: [editRowTask.id, addRowTask.id],
				triggerMode: TaskTriggerMode.Or,
			} as TaskOptions;
			childTaskList[i] = new Task(childTaskOptList[i]);

			submitTaskActionList[i] =
				async (context : Context, taskData : { listIndex : number }) => {
					const index = taskData.listIndex;
					await childPageInit(childFormList.value[index]);
					childFormList.value[index].crud.create = [];
					childFormList.value[index].crud.update = [];
					childFormList.value[index].crud.delete = [];
					return true;
				};
			submitTaskOptList[i] = {
				action: submitTaskActionList[i],
				addNow: true,
				id: `submitTask-${i}${timeSuffix}`,
				type: TaskType.REQUEST,
				chainName,
				data: { listIndex: i },
				beforeTask: [childTaskList[i].id],
				triggerMode: TaskTriggerMode.Or,
			} as TaskOptions;
			submitTaskList[i] = new Task(submitTaskOptList[i]);
		}

		let beforeTaskIds = submitTaskList.map(task => task.id);
		let taskTriggerMode = TaskTriggerMode.And;
		if (beforeTaskIds.length === 0) {
			beforeTaskIds = [editRowTask.id, addRowTask.id];
			taskTriggerMode = TaskTriggerMode.Or;
		}
		const refreshTask = pageRefreshTask(
			'refreshTask' + timeSuffix,
			chainName,
			beforeTaskIds,
			taskTriggerMode
		)
		return refreshTask.id;
	}

	async function getCurrentParams(
		params : { [key : string] : any },
		injectedAPI : { [key : string] : any } = {},
	) : Promise<{ [key : string] : any; }> {
		const currentParams : { [key : string] : any } = {};
		for (const key in params) {
			if (params.hasOwnProperty(key)) {
				currentParams[key] = await run(params[key], injectedAPI);
			}
		}
		return currentParams;
	}

	function pageRefreshTask(
		id : string,
		chainName : string,
		beforeTask : string[],
		triggerMode : TaskTriggerMode = TaskTriggerMode.And,
	) : Task {
		const action = async (context : Context, data ?: unknown) => {
			await refreshPage();
			return true;
		}
		const opt = {
			action: action,
			addNow: true,
			id,
			chainName,
			beforeTask,
			triggerMode,
		} as TaskOptions;
		return new Task(opt);
	}

	function pageRedirect(
		menuOpt : { [key : string] : any },
		url : string
	) {
		inventoryStore.MenuDetail = menuOpt;
		uni.navigateTo({ url });
	}
</script>


<style lang="scss">
	/* #ifdef MP-WEIXIN */
	view {
		box-sizing: border-box;
		margin: 0;
		padding: 0;
	}

	/* #endif */

	/* #ifndef MP-WEIXIN */
	* {
		box-sizing: border-box;
		margin: 0;
		padding: 0;
	}

	/* #endif */


	.u-popup {
		flex: initial !important;
	}

	.page__content {
		height: 100vh;
		background-color: #f9f9f9;

		// .navbar--left {
		// 	:deep(.u-icon) {
		// 		margin-right: 20rpx !important;
		// 	}
		// }

		&__top {
			// flex: 1;
			height: 38.2vh !important;
			overflow: auto;
			// padding: 10px;

			// 表单1
			// .u-form {
			// padding: 0px 10px;
			// }

			// ::v-deep .u-form-item {
			// 	background-color: #fff;
			// 	padding: 0 16px !important;
			// }


			.TopOption {

				.u-form-item__body {
					flex-direction: column !important;
				}
			}
		}

		.content_main {
			flex: 1;
			position: relative;


			.TopCard {
				background-color: #4499ec;

				.CardInfo {
					flex: 3;
				}

				.CardTag {
					position: absolute;
					right: 20px;
					top: 25rpx;

				}
			}
		}

		.common__box {

			&__child {
				&__card__content {
					&__field {
						&__label {
							color: #999;
						}

						&__value {
							margin-left: 10rpx;
							color: #999;
						}
					}
				}

			}


			&__field {
				background-color: #fff;
				padding: 8rpx 15rpx;

				&__label {
					color: #999;
				}

				&__value {
					margin-left: 10rpx;
					color: #999;
				}
			}

		}

		.DetailBox {
			height: 61.8vh !important;
			background-color: #fff;
		}

		.DetailBoxFull {
			height: 100vh !important;
			background-color: #fff;
		}

	}

	.content_bottom1 {
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		height: 70px;
		line-height: 70px;
		padding: 6px 15px;
		// border-top: 1px solid #efefef;
		box-shadow: 1px 0 12px -9px #333;
		z-index: 99;

		.workBtn {
			border-color: #ddd !important;
			margin-left: 10px !important;

			&.small-font {
				font-size: 12px !important;
			}

			&:not(.small-font) {
				font-size: 14px;
			}
		}
	}

	.mainForm {
		height: 38.2vh;
		overflow-y: auto;
	}

	.van-badge {
		margin: 0px 5px;
		background-color: #51d0d0;
		color: #fff;
		display: block;
		min-width: 25px;
		height: 25px;
		line-height: 25px;
		// padding: 3px;
		float: left;
		vertical-align: middle;
		border-radius: 8px;
		text-align: center;
	}

	.editDetail {
		max-height: 50vh;
		overflow-y: auto;
		padding: 5px;

		.editDetail-formBox {
			flex: 1;
			overflow: auto;
			width: 100%;
			// padding: 10px 10px 10px 15px;
		}
	}

	.Main_CardListBox {
		height: calc(61.8vh - 90px);
		overflow: auto;
	}

	.Main_CardListBoxFull {
		height: calc(100vh - 220px);
		overflow: auto;
	}

	.childBtns {
		width: 100%;
		padding: 0 0 10px;
		display: flex;
		align-items: center;
		justify-content: flex-end;

		/* #ifdef MP-WEIXIN */
		button {
			margin: initial;
		}

		/* #endif */
	}
</style>